Servlets - SPLessons

Servlet Sending Email

Home > Lesson > Chapter 40
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet Sending Email

Servlet Sending Email

shape Description

Servlet Sending Email, To send a mail through the code is always an easy and interesting task but here developer has to use localhost servers such as SMTP servers. JavaMail API is the concept related to email through the JavaMail. By using JavaMail API sending, receiving, deleting, managing the email. JavaMail API is platform, protocol independent framework for to send or receive mail. JavaMail API also provides core classes for to define objects and used that objects to maintain a mail system. Following is an example which describes more about how to send the email by using servlet technology. SMTP is a TCP/IP protocol utilized as a part of sending and getting email. since it is constrained in its capacity to line messages at the less than desirable end, it is typically utilized with one of two different conventions, POP3 or IMAP, that let the client spare messages in a server letter box and download them intermittently from the server. At the end of the day, clients ordinarily utilize a program that utilizations SMTP for sending email and either POP3 or IMAP for accepting email. On Unix-based frameworks, sendmail is the most broadly utilized SMTP server for email. A business bundle, Sendmail, incorporates a POP3 server. Microsoft Exchange incorporates a SMTP server and can likewise be set up to incorporate POP3 support.

shape Conceptual figure

Architecture for JavaMail API is shown below: From the above figure, the JavaMail API uses the java application to send, receive, compose the email. It also uses the Server Provider Interface (SPI) to provide the intermediate services to java application, because of this JavaMail API can deal with many protocols.

shape Example

Following is the example to send the mail by using servlet concept. EmailServlet.java [java]import java.io.*; import java.net.*; import java.util.Properties; import javax.mail.AuthenticationFailedException; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.*; import javax.servlet.http.*; public class EmailServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final String err = "/error.jsp"; final String succ = "/success.jsp"; String from = request.getParameter("from"); String to = request.getParameter("to"); String subject = request.getParameter("subject"); String message = request.getParameter("message"); String login = request.getParameter("login"); String password = request.getParameter("password"); try { Properties props = new Properties(); props.setProperty("mail.host", "smtp.gmail.com"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.starttls.enable", "true"); Authenticator auth = new SMTPAuthenticator(login, password); Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setText(message); msg.setSubject(subject); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Transport.send(msg); } catch (AuthenticationFailedException ex) { request.setAttribute("ErrorMessage", "Authentication failed"); RequestDispatcher dispatcher = request.getRequestDispatcher(err); dispatcher.forward(request, response); } catch (AddressException ex) { request.setAttribute("ErrorMessage", "Wrong email address"); RequestDispatcher dispatcher = request.getRequestDispatcher(err); dispatcher.forward(request, response); } catch (MessagingException ex) { request.setAttribute("ErrorMessage", ex.getMessage()); RequestDispatcher dispatcher = request.getRequestDispatcher(err); dispatcher.forward(request, response); } RequestDispatcher dispatcher = request.getRequestDispatcher(succ); dispatcher.forward(request, response); } private class SMTPAuthenticator extends Authenticator { private PasswordAuthentication authentication; public SMTPAuthenticator(String login, String password) { authentication = new PasswordAuthentication(login, password); } protected PasswordAuthentication getPasswordAuthentication() { return authentication; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }[/java] This is the servlet that tries to send the email. The developer will get the necessary parameters from the request. [java]String from = request.getParameter("from"); String to = request.getParameter("to"); String subject = request.getParameter("subject"); String message = request.getParameter("message"); String login = request.getParameter("login"); String password = request.getParameter("password"); [/java] The properties class is utilized for setup. Notice that developer set the validation property to true. [java]Properties props = new Properties(); props.setProperty("mail.host", "smtp.gmail.com"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.starttls.enable", "true");[/java] The developer create a new Authentication class to check the login and the password. [java] Authenticator auth = new SMTPAuthenticator(login, password);[/java] The developer create a new mail session. [java]Session session = Session.getInstance(props, auth);[/java] The developer set the text of the message, subject, sender and recipient email addresses. [java]MimeMessage msg = new MimeMessage(session); msg.setText(message); msg.setSubject(subject); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Transport.send(msg);[/java] Numerous things may turn out badly, while sending an email. For instance developer may give a wrong email address or the confirmation falls flat. Here we respond to an AuthenticationFailedException. On the off chance that we get such a special case, we set an ErrorMessage credit to the solicitation and forward to the error.jsp record. [java]} catch (AuthenticationFailedException ex) { request.setAttribute("ErrorMessage", "Authentication failed"); RequestDispatcher dispatcher = request.getRequestDispatcher(err); dispatcher.forward(request, response); }[/java] index.jsp [java]<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Sending email</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body style="background:#80BFFF"> <center> <form action="./EmailServlet"> <table> <tr> <td>From</td> <td><input type="text" name="from"></td> </tr> <tr> <tr> <td>To</td> <td><input type="text" name="to"></td> </tr> <tr> <td>Subject</td> <td><input type="text" name="subject"></td> </tr> <tr> <td>Message</td> <td><textarea cols="25" rows="8" name="message"></textarea></td> </tr> <tr> <td>Login</td> <td><input type="text" name="login"></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password"></td> </tr> </table> <br> <input type="submit" value="submit"> </form> </center> </body> </html>[/java] Here the developer just created required text boxes to send an email. success.jsp [java]<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Message</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <center> <div class="msg"> <h2>Message</h2> <p> Email sent </p> </div> </center> </body> </html>[/java] If the mail is sent successfully message will be printed that is Email sent. error.jsp [java]<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Error</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <center> <div class="error"> <h2>Error</h2> <p> Message: <%= request.getAttribute("ErrorMessage") %> </p> </div> </center> </body> </html>[/java] Numerous things may turn out badly, while sending an email. For instance developer may give a wrong email address or the confirmation falls flat. Here we respond to an AuthenticationFailedException. On the off chance that we get such a special case, we set an ErrorMessage credit to the solicitation and forward to the error.jsp record. web.xml [xml]<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>mail</servlet-name> <servlet-class>com.splesson.EmailServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mail</servlet-name> <url-pattern>/EmailServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>[/xml] Code will be compiled from the welcome file that is index.jsp, make sure that servlet name should be same in web.xml. Output When compile the program following is the output displayed where user has to enter log in details. After entering the details click on button then mail will be sent. When click on submit button following message will be displayed Now check the mail.

Summary

shape Key Points

  • Servlet Sending Email - By using JavaMail API sending, receiving, deleting, managing and composing the email.
  • Servlet Sending Email - JavaMail API is the concept related to email through the JavaMail.
  • Give the correct port number to the local host server.