Email sending web application using java || JavaMail API.

How to send email in java using JSP and servlet. How to use the JavaMail API and SMTP. Java code to send email using Java mail API.

During the Java web development sometimes we need to send mail to the user to verify some OPT or reset the password. To handle this kind of situation java provide Java mail API. Let’s see some easy steps to achieve this using Java mail API.

Download Java Mail API

If you are using a dynamic java project you can download the Java mail API jar from the official site of oracle Download jar. If you are working on a Maven project then add the below dependency to get the Java mail API support.

<dependency>
 <groupId>javax.mail</groupId>
 <artifactId>mail</artifactId>
 <version>1.4.7</version>
</dependency>

Design an HTML form

This form is designed to get the email as input from the user and when the user will submit this form request will send to the servlet (MailCtl.java).

index.jsp

<%@page import="mypack.MailCtl"%>

<html>
<style> 
div{
background-color: #7DB8F3;
padding-bottom: 200px;

}
input,textarea{
    width: 100%;
    padding: 20px;
    margin-bottom:20px;
    box-sizing: border-box;
    font-size: 20px;
    font-family: "Times New Roman";
    
}
.mg{
    width: 100%;
    padding: 15px 20px;
    margin: -2px 0;
    box-sizing: border-box;
    height: 213px;
}
.button{
    background-color: #3776B7;
    border: none;
    color: white;
    margin-top:20px;
    padding: 12px 58px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    cursor: pointer;
  
}
h1{
color:#ffffff;
font-size: 50px;
margin-bottom: -50px;
margin-top: -15px;
}
</style>
</head>
<body>
<form action="MailCtl" method="post">

<div align="center">
<br><br>
  
  <h1>Email Send Web Application</h1>
  <br><br><br>
  <h3>
    <%String msg=(String)request.getAttribute("msg");%>
    <font color="green"><%=(msg!=null)?msg:""%></font>
  </h3>
  
  <table style="width: 50% ;">
  <tr>
  <th><input   type="text" name="email" placeholder="Email To.. "></th>
  </tr>
  <tr>
  <th><input type="text" name="subject" placeholder="Subject... "></th>
  </tr>
  <tr>
  <th><textarea class="mg" rows="2" cols="6" name="message" placeholder="Email Body..."></textarea></th>
  </tr>
  
  <tr>
  <th align="left"><input  class="button" type="submit" name="operation" value="<%=MailCtl.OP_GO%>"></th>
  </tr>
  </table>
</div>	
  

</form>
</body>
</html>

Email sending web application using java

MailCtl is a servlet that is used to get the request from index.jsp and communicate with EmailUility.java to send mail and send the response back to index.jsp

Create servlet (MailCtl.java)

package mypack;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/MailCtl")
public class MailCtl extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
  public static final String OP_GO="Go";

    public MailCtl() {
        super();
        // TODO Auto-generated constructor stub
    }


  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);
  }


  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
    String email=request.getParameter("email");
    String subject=request.getParameter("subject");
    String message=request.getParameter("message");
    
    String op=request.getParameter("operation");
    
    if(OP_GO.equalsIgnoreCase(op)){
      
    EmailMessage msg = new EmailMessage();
    msg.setTo(email);
    msg.setSubject(subject);
    msg.setMessage(message);
    msg.setMessageType(EmailMessage.HTML_MSG);
    try {
    
      EmailUtility.sendMail(msg);
      
      request.setAttribute("msg","Mail has been Send sucessfully");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);
  }

}

(Simple Java Class)EmailUtility.java

package mypack;


import java.util.Properties;
import java.util.ResourceBundle;
 

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.omg.CORBA.portable.ApplicationException;


public class EmailUtility
{
  
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

     private static Properties props = new Properties();

    static {
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.socketFactory.port",465);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.starttls.enable", "true");
    }
 
    public static void sendMail(EmailMessage emailMessageDTO) throws ApplicationException{
    	 String sender_Email = "User_name";
    	 String sender_email_pass = "Pass";
 
        try {
 
            // Connection to Mail Server
            Session session = Session.getDefaultInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(sender_Email,sender_email_pass);
                        }
                    });
 
     
            session.setDebug(true);
 
            // Create a message
            Message msg = new MimeMessage(session);
            InternetAddress addressFrom = new InternetAddress(sender_Email);
            msg.setFrom(addressFrom);
 
            // Set TO addresses
            String[] emailIds = new String[0];
 
            if (emailMessageDTO.getTo() != null) {
                emailIds = emailMessageDTO.getTo().split(",");
            }
 
            // Set CC addresses
            String[] emailIdsCc = new String[0];
 
            if (emailMessageDTO.getCc() != null) {
                emailIdsCc = emailMessageDTO.getCc().split(",");
            }
 
            // Set BCC addresses
            String[] emailIdsBcc = new String[0];
 
            if (emailMessageDTO.getBcc() != null) {
                emailIdsBcc = emailMessageDTO.getBcc().split(",");
            }
 
            InternetAddress[] addressTo = new InternetAddress[emailIds.length];
 
            for (int i = 0; i < emailIds.length; i++) {
                addressTo[i] = new InternetAddress(emailIds[i]);
            }
 
            InternetAddress[] addressCc = new InternetAddress[emailIdsCc.length];
 
            for (int i = 0; i < emailIdsCc.length; i++) {
                addressCc[i] = new InternetAddress(emailIdsCc[i]);
            }
 
            InternetAddress[] addressBcc = new InternetAddress[emailIdsBcc.length];
 
            for (int i = 0; i < emailIdsBcc.length; i++) {
                addressBcc[i] = new InternetAddress(emailIdsBcc[i]);
            }
 
            if (addressTo.length > 0) {
                msg.setRecipients(Message.RecipientType.TO, addressTo);
            }
 
            if (addressCc.length > 0) {
                msg.setRecipients(Message.RecipientType.CC, addressCc);
            }
 
            if (addressBcc.length > 0) {
                msg.setRecipients(Message.RecipientType.BCC, addressBcc);
            }
 
            // Setting the Subject and Content Type
            msg.setSubject(emailMessageDTO.getSubject());
 
            // Set message MIME type
            switch (emailMessageDTO.getMessageType()) {
            case EmailMessage.HTML_MSG:
                msg.setContent(emailMessageDTO.getMessage(), "text/html");
                break;
            case EmailMessage.TEXT_MSG:
                msg.setContent(emailMessageDTO.getMessage(), "text/plain");
                break;
 
            }
 
            // Send the mail
            Transport.send(msg);
 
        } catch (Exception ex) {
            
        }	
    }
}

EmailMessage.java

EmailMessage.java is bean class is used as getter and setter.

package mypack;


/**
 * Contains Email Message
 *
 * @author Navigable Set
 * @version 1.0
 * @Copyright (c) Navigable Set
 *
 */
public class EmailMessage 
{
   /**
     * Contains comma separated TO addresses
     */
    private String to = null;

    /**
     * Sender addresses
     */
    private String from = null;

    /**
     * Contains comma separated CC addresses
     */
    private String cc = null;

    /**
     * Contains comma separated BCC addresses
     */
    private String bcc = null;

    /**
     * Contains message subject
     */
    private String subject = null;

    /**
     * Contains message
     */
    private String message = null;

    /**
     * Type of message whether it is Htnl or text, default is Text
     */
    private int messageType = TEXT_MSG;

    public static final int HTML_MSG = 1;

    public static final int TEXT_MSG = 2;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    public String getBcc() {
        return bcc;
    }

    public void setBcc(String bcc) {
        this.bcc = bcc;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getMessageType() {
        return messageType;
    }

    public void setMessageType(int messageType) {
        this.messageType = messageType;
    }
}

Download Complete Source code: Email Sending web application Java

Java web application development tutorial

You May Also Like These Posts:

Leave a Reply

Your email address will not be published.

13 + one =