While building Web sites, Java developers have to sometimes provide
functionality of allowing user to submit feedback by an email account; or a
functionality wherein logged-in users can send messages as emails to customers
or clients from a common account. For providing such functionality there's a
Java API called JavaMail API. It provides a mail and messaging framework that
can be used to send messages from the host mail server. For cases where the
website hosting provider does not provide a mail server, developers are forced
to save the users' feedback to a database and retrieve information from there
later. In such a situation Google Mail comes to the rescue. In this article we
will see through a demo app how to incorporate a user's feedback form submission
through the JavaMail API and the feedback data being sent to a Gmail account.
Direct Hit! |
Applies To: Java developers USP: Get forms submitted through emails Primary Link: java.sun.com/products/javamail/downloads/index.html Keywords: JavaMail API On CD: \labs\JavaMail |
About JavaMail API
JavaMail API provides a complete set of abstract classes defining objects that
would comprise a complete mail system. With this API, Java has given developers
a platform from which they can create their own mailing system app that can not
only send but also receive messages. The JavaMail API has support for different
messaging system implementations like Message class for messaging details such
as subject line, etc, store class for different message privileges like read,
write, etc, and Transport class for message sending over a particular protocol.
JavaMail subclasses also expose additional messaging system features, for
instance, the MimeMessage sub class that exposes and implements characteristics
of an Internet mail message that are as per RFC822 and MIME standards.
Developers can now subclass the JavaMail classes to provide them with
implementations for particular messaging systems, such as IMAP, POP3, and SMTP.
By using these abstract classes the base can be configured for defining the
client application for a messaging system.
Setup and Configuration
For the demo app we will build a component of the website that will have a
feedback form designed in JSP, which we'll call the 'Java Servlet.' This will
use JavaMail to send the form-data as an email. The web server for the demo will
be Tomcat. For this purpose let's first do some basic configuration of the APIs.
With this month's PCQ_PRFESSIONAL CD we have provided JavaMail API version 1.4
along with Java Activation Framework (JAF) version 1.1.1 zip files. Extract the
zip files to some base folder and then append the paths to the Classpath entry
for system environment variables pointing to mail.jar under JAVA_MAIL/bin folder
and activation.jar under JAF/bin folder.
Now from within Eclipse IDE start a new project from File > New > Project and
then select Tomcat project (considering that the Tomcat-Eclipse plug-in is
installed). Name the project as 'JavaMail.' As we intend to deploy our app on a
hosting service provider's server, we will have to pack the JavaMail APIs into
the WAR file so that during deployment the programs could get reference to the
JavaMail libraries. For this reason copy the mail.jar and activation.jar files
into the WEB-INF/lib folder. Also add these two jar files into the project's
classpath. Once this initial configuration of the project 'JavaMail' has been
completed we can now start building our Web app.
Packing the mail and activation JAR files result in their avilabity on remote host |
Designing the form and its Servlet
The feedback form for the demo app is simple with two input fields for
taking sender's e-mail address and his name, while the text area will be used
for taking the user's feedback/comment. Name the fields appropriately so that
their values can be retrieved by the Servlet while sending the mail. On the
form's action attribute set the mapped path that will call for the Servlet. Now
let's start coding for the Servlet that will retrieve the values from the
feedback form and will send them across to an email account
For the demo app we are using Google Mail as the mail server to send mails.
To send mails via Gmail, the SMTP mail protocol is used and the port for that on
Gmail server is 465 and the host is smtp.gmail.com. The email account we refer
here as 'demoaccount' is just for reference. Also Google only allows messages to
be sent over SSL, so we will have to enable it. Also we have to login into the
Gmail account and after authentication only the mail could be sent, so for this
we will use Authentication also and set the property for that as true. Once the
message is sent the transporter waits for a QUIT command, we can close the
connection immediately by setting the quitwait property as false. Now with
initial properties configured, we can proceed by sending the message. Let's look
at the demo Servlet first then we will discuss some of the parameters used in
that.
public class SendMailServlet extends HttpServlet
{ ...
public void service(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException{ senderName=request.getParameter("name");
comment=request.getParameter("comment");
String to="demoaccount@gmail.com";
String from="demoacc@gmail.com";
String host = "smtp.gmail.com";
Properties p = new Properties();
p.put("mail.smtp.host", host);
p.put("mail.smtp.port", "465");
p.put("mail.smtp.starttls.enable","true");
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.debug", "true");
p.put("mail.smtp.socketFactory.port", "465");
p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.socketFactory.fallback", "false");
p.put("mail.debug", "true");
p.setProperty("mail.smtp.quitwait", "false");
SecurityManager security = System.getSecurityManager();
try {Authenticator auth = new SMTPAuthenticator(); Session session = Session.
getInstance(p, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress<> address = {new InternetAddress(to)};
msg.setRecipints(Message.RecipientType.TO, address);
msg.setSubject("Test Mail");
msg.setSentDate( new Date() );
message.setContent(comment,“mptext/plain");
msg.saveChanges();
Transport.send(msg);
System.out.println("Mail Send Successfully....");
}
catch (MessagingException mex) { mex.printStackTrace();
System.out.println("Mail not sent");}
} //service ends here}
For the above code mention the init() and destroy() method also. Then in the
Properties we have set all the parameters for forwarding the mail. The
MimeMessage initiates the session that will use the Properties parameters and
set the values from the feedback form and configure the message body. The
Transport will send the message over the set protocol, in our case SMTP. As we
use Authenticator class named as SMTPAuthenticator for password verification,
let's define the same.
class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( "demoaccount", "password");
}
This way we can use JavaMail to send the feedback of a user as e-mail message
to a Gmail account. Even when the web hosting provider does not facilitate you
with a mail server you have JavaMail and Gmail to implement the mailing system
for Web app.
In Conclusion
JavaMail API provides facility with which a developer can configure a complete
mail system for sending/receiving mails over standard mail protocols. It's a
great way to enhance your Web applications.