The Commons Email is built on top of the Java Mail API, which
basically simplifies the whole process of sending an email. With the
help of HTMLEmail class in commons you can send HTML formatted email. It
has all of the capabilities as MultiPartEmail allowing attachments to
be easily added and also supports embedded images. In this tutorial we
have created a contact US form in JSP so that we can check the
capabilities of this very userful API. To send an email we need a SMTP
server, from Email address, to Email address and a Subject. If your SMTP
server needs authetication then you have to provide the login
credentials.
For this example we are using gmail as our SMTP server. To create the HTML content that needs to go in the message body we have taken help of the WYSIWYG editor based on jQuery named jWysiwyg. You can read more about this editor at http://akzhan.github.com/jwysiwyg/. Following jars in your project classpath for this example to work
Source for the JSP - htmlEmail.jsp
Source for the Java Servlet - SendHTMLEmail.java
References
For this example we are using gmail as our SMTP server. To create the HTML content that needs to go in the message body we have taken help of the WYSIWYG editor based on jQuery named jWysiwyg. You can read more about this editor at http://akzhan.github.com/jwysiwyg/. Following jars in your project classpath for this example to work
- commons-email-1.2.jar (http://commons.apache.org/email/download_email.cgi)
- mail.jar (http://www.oracle.com/technetwork/java/javamail/index.html)
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=ISO-8859-1" > <meta name= "robots" content= "noindex,nofollow" /> <title>HTML email using Apache Commons API</title> <link rel= "stylesheet" href= "/resources/themes/master.css" type= "text/css" /> <link rel= "stylesheet" href= "/resources/themes/jquery.wysiwyg.css" type= "text/css" /> <link rel= "stylesheet" type= "text/css" /> <script type= "text/javascript" ></script> <script type= "text/javascript" ></script> <script type= "text/javascript" ></script> <script src= "/resources/scripts/mysamplecode.js" type= "text/javascript" ></script> <script type= "text/javascript" src= "/resources/scripts/jquery.wysiwyg.js" ></script> <script type= "text/javascript" > $(document).ready( function () { $( "#samplecode" ).validate({ rules: { mailServer: "required" , fromName: "required" , fromEmail: "required" , toName: "required" , toEmail: "required" , subject: "required" , password: { required: function (element) { return $.trim($( "#userId" ).val()) != '' ; } } } }); $( function (){ $( '#messageBody' ).wysiwyg(); $( '#messageBody' ).wysiwyg( 'clear' ); }); }); </script> </head> <body> <div id= "allContent" > <%@include file= "/header.jsp" %> <div id= "myContent" > <div> <% boolean success = false ; if (request.getAttribute( "success" ) != null ){ success = (Boolean) request.getAttribute( "success" ); } if (success){ %> <font color= "green" > <b><br/>Thank you! You message has been sent.</b> <br/> </font> <% } else { if (request.getAttribute( "success" ) != null ){ %> <font color= "red" > <b><br/>Error! You message was not sent.</b> <br/> </font> <% } } %> </div> <form id= "samplecode" name= "samplecode" method= "POST" action= "<%= request.getContextPath() %>/SendHTMLEmail" > <fieldset> <legend><b> HTML
Email using Apache Commons
API </b></legend> <table> <tr> <td> <label for = "mailServer" > Mail Server Host Name </label> </td> <td> <input id= "mailServer" type= "text" name= "mailServer" size= "50" value= "smtp.gmail.com" /> </td> </tr> <tr> <td> <label for = "userId" > Mail Server User Id </label> </td> <td> <input id= "userId" type= "text" name= "userId" size= "30" value= "" /> <i>(In case your mail server needs Authentication)</i> </td> </tr> <tr> <td> <label for = "password" > Mail Server Password </label> </td> <td> <input id= "password" type= "password" name= "password" size= "30" value= "" /> <i>(In case your mail server needs Authentication)</i> </td> </tr> <tr> <td colspan= "2" > </td> </tr> <tr> <td> <label for = "fromName" > Sender 's Name </label> </td> <td> <input id="fromName" type="text" name="fromName" size="30" value=""/> </td> </tr> <tr> <td> <label for="fromEmail"> Sender' s Email Address </label> </td> <td> <input id= "fromEmail" type= "text" name= "fromEmail" size= "50" value= "" /> </td> </tr> <tr> <td> <label for = "toName" > Recipient 's Name </label> </td> <td> <input id="toName" type="text" name="toName" size="30" value=""/> </td> </tr> <tr> <td> <label for="toEmail"> Recipient' s Email Address </label> </td> <td> <input id= "toEmail" type= "text" name= "toEmail" size= "50" value= "" /> </td> </tr> <tr> <td colspan= "2" > </td> </tr> <tr> <td> <label for = "subject" > Subject </label> </td> <td> <input id= "subject" type= "text" name= "subject" size= "50" value= "" /> </td> </tr> <tr> <td class= "formText" > <label for = "messageBody" > Message </label> </td> <td> <textarea id= "messageBody" name= "messageBody" rows= "10" cols= "100" maxlength= "1000" ></textarea> </td> </tr> <tr> <td class= "formText" > </td> <td> <input id= "sendEmail" type= "submit" value= "Send my Email" /> </td> </tr> </table> </fieldset> </form> </div> </div> <%@include file= "/footer.jsp" %> <div></div> </body> </html> |
Source for the Java Servlet - SendHTMLEmail.java
package com.as400samplecode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; public class SendHTMLEmail extends HttpServlet { private static final long serialVersionUID = 1L; public SendHTMLEmail() { super (); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mailServer = request.getParameter( "mailServer" ).trim(); String userId = request.getParameter( "userId" ).trim(); String password = request.getParameter( "password" ).trim(); String fromName = request.getParameter( "fromName" ).trim(); String fromEmail = request.getParameter( "fromEmail" ).trim(); String toName = request.getParameter( "toName" ).trim(); String toEmail = request.getParameter( "toEmail" ).trim(); String subject = request.getParameter( "subject" ).trim(); String messageBody = request.getParameter( "messageBody" ).trim(); StringBuilder sb = new StringBuilder(); sb.append( "<html>" ); sb.append( "<body>" ); sb.append( "<table>" ); sb.append(messageBody); sb.append( "</table>" ); sb.append( "</body>" ); sb.append( "</html>" ); try { // Sending HTML formatted email HtmlEmail htmlEmail = new HtmlEmail(); // set the address of the outgoing SMTP server that will be used to send the email htmlEmail.setHostName(mailServer); // set to true if you want to debug htmlEmail.setDebug( true ); // if the SMTP server needs authentication if (!userId.trim().equalsIgnoreCase( "" ) && !password.trim().equalsIgnoreCase( "" )){ htmlEmail.setAuthenticator( new DefaultAuthenticator(userId, password)); htmlEmail.setTLS( true ); } // set the recipient htmlEmail.addTo(toEmail, toName); // set the sender htmlEmail.setFrom(fromEmail, fromName); // set the subject htmlEmail.setSubject(subject); // set the email body htmlEmail.setHtmlMsg(sb.toString()); // finally send the email htmlEmail.send(); request.setAttribute( "success" , true ); } catch (EmailException e) { request.setAttribute( "success" , false ); e.printStackTrace(); } getServletContext().getRequestDispatcher( "/pages/htmlEmail.jsp" ).forward(request, response); } } |