Wednesday, October 21, 2009

Recipe 20.3 Sending Email from a Servlet Using a JavaBean



[ Team LiB ]






Recipe 20.3 Sending Email from a Servlet Using a JavaBean




Problem



You want to use a
JavaBean or helper class to send email from a servlet.





Solution



Develop a Java class that implements a sendMessage(
)
method (just a name I gave it) to construct an email and
send it. Store the new class in the
WEB-INF/classes folder of the web application,
including the class's package-related folders.





Discussion



You may choose to separate the responsibilities of handling HTTP
requests and managing email by encapsulating these tasks in separate
classes. A JavaBean that provides the essential function of sending
email fits the bill here.






Recipe 20.5 and Recipe 20.6
show JavaBeans that are used to access email and
handle attachments. A bean that does everything
email-related grows fairly large in size, so developers
must make a design decision about whether to separate these tasks
into different JavaBeans (or utility classes) that can be used from
servlets.





Create the bean and store it in the
WEB-INF/classes folder. Example 20-3 shows the doGet(
)
method of an
HttpServlet using a JavaBean to send an email.
Example 20-2 shows the bean class itself. The
difference between the sendMessage( ) method of
Example 20-1 and the one in Example 20-2 is in the way the bean receives the various
email parts, such as the recipient's email address.
The bean stores these parts as
properties and uses setter
methods to provide the property values.






On the other hand, Example 20-1 uses request
parameters and method arguments to provide these values.






Example 20-2. A JavaBean used to send email

package com.jspservletcookbook;    

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;


public class EmailBean {

public EmailBean( ){}

//set defaults
private final static String DEFAULT_CONTENT = "Unknown content";
private final static String DEFAULT_SUBJECT= "Unknown subject";
private static String DEFAULT_SERVER = null;
private static String DEFAULT_TO = null;
private static String DEFAULT_FROM = null;
static{
//set Mail defaults based on a properties file
java.util.ResourceBundle bundle =
java.util.ResourceBundle.
getBundle("com.jspservletcookbook.mailDefaults");

DEFAULT_SERVER = bundle.getString("DEFAULT_SERVER");
DEFAULT_TO = bundle.getString("DEFAULT_TO");
DEFAULT_FROM = bundle.getString("DEFAULT_FROM");

}//static


//JavaBean properties
private String smtpHost;
private String to;
private String from;
private String content;
private String subject;

public void sendMessage( ) throws Exception {

Properties properties = System.getProperties( );

//populate the 'Properties' object with the mail
//server address, so that the default 'Session'
//instance can use it.
properties.put("mail.smtp.host", smtpHost);
Session session = Session.getDefaultInstance(properties);
Message mailMsg = new MimeMessage(session);//a new email message
InternetAddress[] addresses = null;


try {


if (to != null) {

//throws 'AddressException' if the 'to' email address
//violates RFC822 syntax
addresses = InternetAddress.parse(to, false);
mailMsg.setRecipients(Message.RecipientType.TO, addresses);


} else {

throw new MessagingException(
"The mail message requires a 'To' address.");

}

if (from != null) {

mailMsg.setFrom(new InternetAddress(from));

} else {

throw new MessagingException(
"The mail message requires a valid 'From' address.");

}

if (subject != null)
mailMsg.setSubject(subject);

if (content != null)
mailMsg.setText(content);

//Finally, send the mail message; throws a 'SendFailedException'
//if any of the message's recipients have an invalid address
Transport.send(mailMsg);


} catch (Exception exc) {

throw exc;

}

}//sendMessage

//The setter methods are all the same structure,
//so we're just showing two


public void setSmtpHost(String host){

if (check(host)){
this.smtpHost = host;
} else {
this.smtpHost = DEFAULT_SERVER;
}

}//setSmtpHost

public void setTo(String to){

if (check(to)){
this.to = to;
} else {
this.to = DEFAULT_TO;
}

}//setTo

/* -- Not shown: 'setter' methods continue with exactly the same structure for
'from', 'subject', and 'content' -- */

private boolean check(String value){

if(value == null || value.equals(""))
return false;

return true;
}//check

}



Example 20-3 uses the
java.util.ResourceBundle
class to set default property values for
variables such as the name of the server. The
mailDefaults.properties
file is stored in
WEB-INF/classes/com/jspservletcookbook. Here is
an example of the properties file's contents:



DEFAULT_SERVER=smtp.comcast.net
DEFAULT_TO=author@jspservletcookbook.com
DEFAULT_FROM=author@jspservletcookbook.com


The bean allows the setting of the
various email parts with the following
methods (Example 20-3 does not show all of them):
setSmtpHost( ) , setTo( ),
setFrom( ), setSubject( ), and
setContent( ).



The servlet in Example 20-3 creates an instance of an
EmailBean, sets the various parts of the email
message, then calls the sendMessage( ) method.
Example 20-3 shows only the doGet(
)
method. The
servlet's doPost( ) method could
call doGet( ) as in: doGet(request,
response)
.




Example 20-3. A servlet uses the JavaBean to send email

public void doGet(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, java.io.IOException {

response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
out.println(
"<html><head><title>Email message sender</title></head><body>");

EmailBean emailer = new EmailBean( );
emailer.setSmtpHost("mail.attbi.com");
emailer.setTo("myfriend@yahoo.com");
emailer.setFrom("author@jspservletcookbook.com");
emailer.setSubject("This is not spam!");
emailer.setContent("Please call ASAP.");

try{
emailer.sendMessage( );
} catch (Exception e) {throw new ServletException(e);}


out.println("</body></html>");

} //doGet



The bean itself throws
MessagingExceptions if, for instance, the
"to" email address that the user
provides is in an invalid format. The bean rethrows any exceptions
that it catches while building and sending the email.





See Also



Recipe 20.4 covering how to access email in a
servlet; Recipe 20.5 on accessing email with
a JavaBean; Recipe 20.6 on handling
attachments in a servlet; Recipe 20.7 on
adding attachments to an email message; Recipe 20.8 on reading an email's
headers.








    [ Team LiB ]



    No comments: