您现在的位置:计算机技术学习网 > 技术中心 > WEB编程 > JSP >

在jsp中发送email

来源:网络 责任编辑:栏目编辑 发表时间:2013-07-02 00:36 点击:
在jsp(SUN企业级应用的首选)中发送email

一、我们可以通过任何支持sun规范中的sun.net.smtp包的jsp(SUN企业级应用的首选)引擎(如JSWDK)发送mail。
(警告:使用内置的internal Sun规范包,这将影响到你的jsp(SUN企业级应用的首选)程序的可移植性。)

以下scriptlet利用SmtpClient类在jsp(SUN企业级应用的首选)文件中发送email。





二、 JavaMail是官方的 Java mail API,可参考 http://java.sun.com/products/javamail/。虽然该API比 sun.net.smtp.SmtpClient更丰富或者说更复杂,但它是可移植的。这里重新创建了一个 MailSender类,它包含了 JavaMail API。如下所示:


// ms_ prefix is for MailSender class variables
// str prefix is for String
// astr prefix is for array of Strings
// strbuf prefix is for StringBuffers, etc.
public MailSender(
String strFrom, // sender
String[] astrTo, // recipient(s)
String[] astrBCC, // bcc recipient(s), optional
String strSubject, // subject
boolean debugging)
{
ms_strFrom = strFrom; // who the message is from
ms_astrTo = astrTo; // who (plural) the message is to
ms_debugging = debugging; // who (plural) the message is to

// set the host
Properties props = new Properties();
props.put("mail.smtp.host", ms_strSMTPHost);

// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(ms_debugging);

try {
// create a message
ms_msg = new MimeMessage(session);

// set the from
InternetAddress from = new InternetAddress(strFrom);
ms_msg.setFrom(from);

// set the to
InternetAddress[] address = new InternetAddress[astrTo.length];
for (int i = 0; i astrTo.length; ++i)
{
address[i] = new InternetAddress(astrTo[i]);
}
ms_msg.setRecipients(Message.RecipientType.TO, address);

// set the bcc recipients
if (astrBCC != null)
{
address = new InternetAddress[astrBCC.length];
for (int i = 0; i astrBCC.length; ++i)
{
eh.dbg("astrBCC[" + i + "] is: \" + astrBCC[i] + "\");
address[i] = new InternetAddress(astrBCC[i]);
}
ms_msg.setRecipients(Message.RecipientType.BCC, address);
}

// set the subject
ms_msg.setSubject(strSubject);

// set up the string buffer which will hold the message
ms_strbufMsg = new StringBuffer();

} catch (MessagingException mex) {
mex.printStackTrace(System.err);
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}

public void ms_add(String strText)
{
ms_strbufMsg.append(strText);
}

public void ms_send()
{
try {
// set the content as plain text
ms_msg.setContent(new String(ms_strbufMsg), "text/plain");

// and away
Transport.send(ms_msg);
} catch (Exception ex) {
System.out.println("Caught exception in MailSender.ms_send: " + ex);
}
}

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • JSP与Servlet
      • 自己动手写MiniBBS系列(基本篇)之用户登录
      • JSP取当前日期
      • JDBC 入门(一)
      • 打开一个jsp页面默认查询所有数据,调用action
      • 使用JSP标签库验证用户的输入(2)完
      • WIN98/2000下的jsp服务器
      • 自定义JSP标签(tag)浅议
      • Struts学习傻瓜式入门篇
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1