Send email in jsp
Author:Eve Cole
Update Time:2009-07-02 17:13:09
Send email in jsp
1. We can send mail through any JSP engine (such as JSWDK) that supports the sun.net.smtp package in the sun specification.
(Warning: Use the built-in internal Sun specification package, which will affect the portability of your jsp program.)
The following scriptlet uses the SmtpClient class to send emails in jsp files.
2. JavaMail is the official Java mail API, please refer to http://java.sun.com/products/javamail/. Although the API is richer or more complex than sun.net.smtp.SmtpClient, it is portable. A MailSender class is recreated here, which contains the JavaMail API. As shown below:
// 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);
}
}