Servlet - Sending Email - GeeksforGeeks

31 Mar, 2022
E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That’s the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like – communication, Multi-Factor Authentication, etc.  Working with mailing service within servlet requires – SMTP server(local/remote) and the two following APIs.
Java Mail API (JMA) – javax.mail.jarJavaBeans Activation Framework API (JAF) –  activation.jar
Java Mail API (JMA) – javax.mail.jar
JavaBeans Activation Framework API (JAF) –  activation.jar
Pre-requisites: 
If you use the Gmail SMTP server, the Sign-in attempt can be blocked due to2-step verification is turned on,Less secure app access is turned off.
2-step verification is turned on,
Less secure app access is turned off.
You can either change the google account settings or use Sign-in with Google / Google generated App code.
Understanding mailing service protocols
   Protocols 
Description
     SMTP             
POP
IMAP
MIME
Life-Cycle of Email
Steps to associate Java Mail API:
Download the javax.mail.jar file.Copy the javax.mail.jar file to the application’s WEB-INF\lib directory.Add the javax.mail.jar file to the classpath for your application.
Download the javax.mail.jar file.
Copy the javax.mail.jar file to the application’s WEB-INF\lib directory.
Add the javax.mail.jar file to the classpath for your application.
Steps to associate JavaBeans Activation Framework API:
Download the ZIP file and extract the files.Copy the activation.jar file to the application’s WEB-INF\lib directory.Add the activation.jar file to the classpath for your application.
Download the ZIP file and extract the files.
Copy the activation.jar file to the application’s WEB-INF\lib directory.
Add the activation.jar file to the classpath for your application.
Note: The JavaBeans Activation Framework API is included with Java SE 6. As a result, if you’re using Java SE 6 or later, you don’t need to install this API.
Web-Application (Servlet) Structure:
Association of files in Servlet Web-Application
1] web.xml (configuration)
XML
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.1"    xmlns="http://xmlns.jcp.org/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">    <servlet>        <servlet-name>Email</servlet-name>        <servlet-class>mail.Servlet.Email</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>Email</servlet-name>        <url-pattern>/Email</url-pattern>    </servlet-mapping>    <session-config>        <session-timeout>            30        </session-timeout>    </session-config></web-app>
2] index.html (Entering Details)
HTML
<!DOCTYPE html><html>    <head>        <title>GeeksforGeeks</title>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1.0">    </head>    <body>        <form action="Email" method="post">            <div align="center"> <h1>Enter the Credentials: </h1>            <input type="hidden" name="action" value="add">                        <label for="sID">Sender ID :</label> <br>            <input id="sID" type="text" name="id"> <br>                         <label for="sMail">Sender Email :</label> <br>            <input id="sMail" type="email" name="emailSender"> <br>                        <label for="pw">Password :</label> <br>            <input id="pw" type="password" name="password"> <br>                        <label for="rMail">Receiver Email :</label> <br>            <input id="rMail" type="email" name="emailReceiver"> <br>                         <label for="sub">Subject :</label> <br>            <input id="sub" type="text" name="subject"> <br>                         <label for="message">Message :</label> <br>            <input id="message" type="text" name="message"><br>            <input type="submit" value="Send">                         </div>        </form>    </body></html>
Output:
Fill details in output of Mail.java
3] Email.java (Servlet for handling details)
Java
package mail.Servlet; import static mail.Servlet.Mail.sendMail; import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class Email extends HttpServlet {     protected void    processRequest(HttpServletRequest request,                   HttpServletResponse response)        throws ServletException, IOException    {         String id, sender, receiver, password, subject,            message;         // check if directed url        String action = request.getParameter("action");        String url = "/index.html";        if (action == null) {            // directed to email interface            action = "join";        }        if (action.equals("join")) {            url = "/index.html";        }        if (action.equals("add")) {            // retrieve the entered credentials            id = request.getParameter("id");            sender = request.getParameter("emailSender");            receiver                = request.getParameter("emailReceiver");            password = request.getParameter("password");            subject = request.getParameter("subject");            message = request.getParameter("message");            // get and set String value of email status            request.setAttribute(                "message",                sendMail(id, receiver, sender, subject,                         message, true, password));            // directed to page showing the status of email            url = "/confirmation.jsp";        }         getServletContext()            .getRequestDispatcher(url)            .forward(request, response);    }     @Override    protected void doGet(HttpServletRequest request,                         HttpServletResponse response)        throws ServletException, IOException    {        processRequest(request, response);    }     @Override    protected void doPost(HttpServletRequest request,                          HttpServletResponse response)        throws ServletException, IOException    {        processRequest(request, response);    }     // Returns a short description of the servlet.    // @return a String containing servlet description    @Override public String getServletInfo()    {        return "Short description";    }}
  
4] Mail.java (Helper class for creating and sending mail)
 
Essential classes:
 
Packages
Description
java.util
javax.mail
 
Create and Send an Email Message:
 
Creating Mail Session:
 
You have to create a mail session to create and send an email message.Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).You can use other properties as well to configure mail sessions.Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class.
You have to create a mail session to create and send an email message.
Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.
You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).
You can use other properties as well to configure mail sessions.
Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class.
Common Properties
Description
mail.smtp.host
mail.smtp.port
mail.smtp.auth
mail.smtp.quitwait
// local SMTP server - Default 
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
// local SMTP server - Configure
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
// remote SMTP server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.auth","true");
props.put("mail.smtps.quitwait","false");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
 
Creating Message:
 
To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.You can set the subject, body, and addresses for the message.If the body is other than plain text, use the setContent() method to change the MIME type of message.
To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.
You can set the subject, body, and addresses for the message.
If the body is other than plain text, use the setContent() method to change the MIME type of message.
Message message = new MimeMessage(session);
message.setSubject("Test");
// automatically sets to text/plain
message.setText("Test Successful"); 
message.setContent("<h1>Test Successful<h1>", "text/html");
Note: All of the Message methods used above throws javax.mail.MessagingException.
// add attachments within email

// create 1'st part of body
BodyPart bodyPart = new MimeBodyPart(); 
bodyPart.setText("Body Message");

Multipart multiPart = new MimeMultipart();
// wrap up 1'st part
multiPart.addBodyPart(bodyPart); 

// create 2'nd part of body
bodyPart = new MimeBodyPart(); 
DataSource source = new FileDataSource("Filename.txt");
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName("Filename.txt");

// wrap up 2'nd part.
multiPart.addBodyPart(bodyPart);
// adds wrapped parts in message 
message.setContent(multiPart); 
 
Addressing a message:
 
Create an object of InternetAddress (Sub-class of Address class).The first argument specifies the email address.You can add a second argument to associate an ID or email address to be displayed.To set FROM address. use setFrom(Address add) method of the MimeMessage object.To set TO, CC (carbon copy), BCC  (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object.
Create an object of InternetAddress (Sub-class of Address class).
The first argument specifies the email address.
You can add a second argument to associate an ID or email address to be displayed.
To set FROM address. use setFrom(Address add) method of the MimeMessage object.
To set TO, CC (carbon copy), BCC  (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.
For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object.
// set sender
Address fromAdd = new InternetAddress("from@gmail.com", "from ID");
message.setFrom(fromAdd);
// set recipient
Address toAdd = new InternetAddress("to@gmail.com");
message.setRecipient(Message.RecipientType.TO, toAdd);
message.setRecipient(Message.RecipientType.CC, toAdd);
message.setRecipient(Message.RecipientType.BCC, toAdd);
// set recipients
message.setRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress("to1@gmail.com"),new InternetAddress("to2@gmail.com")});
 
// add recipients
Address toAdd1 = new InternetAddress("to@gmail.com");
message.addRecipient(Message.RecipientType.TO, toAdd1);
Note: When you send a carbon copy, the CC addresses appear in the message. When you send a blind carbon copy, the BCC address doesn’t appear in the message. If you use the two-argument constructor of InternetAddress, it throws the java.io.UnsupportedEncoding Exception.
 
Sending a message:
 
If the SMTP doesn’t require authentication, you can use the static send(Message msg) method of the Transport class to send a message.
 
Transport.send(message);
If the SMTP requires authentication, you can use the getTransport() method of the session object.Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.You need to close the connection using the close() method if not used try-with-resources block.
If the SMTP requires authentication, you can use the getTransport() method of the session object.
Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.
Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.
You need to close the connection using the close() method if not used try-with-resources block.
Transport transport = session.getTransport();
transport.connect("email-id", "password");
transport.sendMessage("message", message.getAllRecipients());
transport.close();
Note: If the SMTP host is incorrect, the – static void send(Message msg) method throws SendFailedException.
 
Java
package mail.Servlet; import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage; public class Mail {    public static String    sendMail(String id, String to, String from,             String subject, String body, boolean content,             String password)    {        String status = null;        try {            // acquire a secure SMTPs session            Properties pros = new Properties();            pros.put("mail.transport.protocol", "smtps");            pros.put("mail.smtps.host", "smtp.gmail.com");            pros.put("mail.smtps.port", 465);            pros.put("mail.smtps.auth", "true");            pros.put("mail.smtps.quitwait", "false");            Session session                = Session.getDefaultInstance(pros);            session.setDebug(true);            // Wrap a message in session            Message message = new MimeMessage(session);            message.setSubject(subject);             if (content) {                message.setContent(body, "text/html");            }            else {                message.setText(body);            }            // specify E-mail address of Sender and Receiver            Address sender = new InternetAddress(from, id);            Address receiver = new InternetAddress(to);            message.setFrom(sender);            message.setRecipient(Message.RecipientType.TO,                                 receiver);            // sending an E-mail            try (Transport tt = session.getTransport()) {                // acqruiring a connection to remote server                tt.connect(from, password);                tt.sendMessage(message,                               message.getAllRecipients());                status = "E-Mail Sent Successfully";            }        }        catch (MessagingException e) {            status = e.toString();        }        catch (UnsupportedEncodingException e) {            status = e.toString();        }        // return the status of email        return status;    }}
  
5] confirmation.jsp (Check the status of email)
 
HTML
<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <title>GeeksforGeeks</title>    </head>    <body>        <h3 align="center">Status of E-Mail : </h3>        <h1 align="center">${requestScope.message}</h1>    </body></html>
Output:
Mail Status after life-cycle
adnanirshad158
sagartomar9927
java-servlet
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java