在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]);