Send email in JSP
1. We can send mail via any JSP Engine (such as jswdk) that supports sun.net. SMTP packages in Sun specifications.
(Warning: Use the built-in internal sun specification package, which will affect your JSPProgram.)
The following scriptlet uses the smtpclient class to send emails to JSP files.
2. javamail is the official Java mail API. For details, refer to http://java.sun.com/products/javamail /. Although this API is richer or more complex than sun.net. SMTP. smtpclient, It is portable. Here, a new mailsender class is created, which contains the javamail API. As follows:
// 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
Ms_debugging = debugging; // who (plural) the message is
// 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
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 );
}
}