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.


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 (


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

background-color: #7DB8F3;
padding-bottom: 200px;

    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    font-size: 20px;
    font-family: "Times New Roman";
    width: 100%;
    padding: 15px 20px;
    margin: -2px 0;
    box-sizing: border-box;
    height: 213px;
    background-color: #3776B7;
    border: none;
    color: white;
    padding: 12px 58px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    cursor: pointer;
font-size: 50px;
margin-bottom: -50px;
margin-top: -15px;
<form action="MailCtl" method="post">

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


Email sending web application using java

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

Create servlet (

package mypack;


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;

public class MailCtl extends HttpServlet {
  private static final long serialVersionUID = 1L;
  public static final String OP_GO="Go";

    public MailCtl() {
        // 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");
    EmailMessage msg = new EmailMessage();
    try {
      request.setAttribute("msg","Mail has been Send sucessfully");
    } catch (Exception e) {
      // TODO Auto-generated catch block
    RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);


(Simple Java Class)

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 = "";

     private static Properties props = new Properties();

    static {
        props.put("", "");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.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);
            // Create a message
            Message msg = new MimeMessage(session);
            InternetAddress addressFrom = new InternetAddress(sender_Email);
            // 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
            // Set message MIME type
            switch (emailMessageDTO.getMessageType()) {
            case EmailMessage.HTML_MSG:
                msg.setContent(emailMessageDTO.getMessage(), "text/html");
            case EmailMessage.TEXT_MSG:
                msg.setContent(emailMessageDTO.getMessage(), "text/plain");
            // Send the mail
        } catch (Exception ex) {
} 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) { = to;

    public String getFrom() {
        return from;

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

    public String getCc() {
        return cc;

    public void setCc(String 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 =