欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在jsp中发送email

程序员文章站 2024-02-25 09:37:34
在jsp中发送email 一、我们可以通过任何支持sun规范中的sun.net.smtp包的jsp引擎(如jswdk)发送mail。 (警告:使用内置的internal s...
在jsp中发送email

一、我们可以通过任何支持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[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);
}
}