职业IT人-IT人生活圈

 找回密码
 成为会员
搜索
查看: 1525|回复: 0

在jsp中发送email

[复制链接]
joe 发表于 2006-11-28 21:16 | 显示全部楼层 |阅读模式
一、我们可以通过任何支持sun规范中的sun.net.smtp包的JSP引擎(如JSWDK)发送mail。
(警告:使用内置的internal Sun规范包,这将影响到你的jsp程序的可移植性。)

以下scriptlet利用SmtpClient类在jsp文件中发送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 = new InternetAddress(astrTo);
}
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 + \\\"\\\'\\\");
address = new InternetAddress(astrBCC);
}
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);
}
}
您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

QQ|手机版|小黑屋|网站帮助|职业IT人-IT人生活圈 ( 粤ICP备12053935号-1 )|网站地图
本站文章版权归原发布者及原出处所有。内容为作者个人观点,并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是信息平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽造成漏登,请及时联系我们,我们将根据著作权人的要求立即更正或者删除有关内容。

GMT+8, 2024-5-11 15:25 , Processed in 0.136064 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表