How to send mail in Java using Mail API, JSP and Servlet

Java mail API, How to send mail in Java using JSP and servlet. How to create an email program in java using Java mail API.

Java provides mail API to perform the mail operation. In this web application development tutorial, We Will see how to implement mail functionality using JSP and servlet. So let’s follow some easy steps to send mail in java.

Steps to send mail in Java.

Step 1) Create a session object.

Store Authentication, and the hostname, port number and create a session object.

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");
  }

    // Connection to Mail Server
           Session session = Session.getDefaultInstance(props,
                   new javax.mail.Authenticator() {
                       protected PasswordAuthentication getPasswordAuthentication() {
                           return new PasswordAuthentication(sender_Email,sender_email_pass);
                       }
           });

Step 2) Compose mail or prepare the message.

// Create a message
Message msg = new MimeMessage(session);

Step 3) Send the message.

Transport.send(msg);

When we implement these three steps in the java application we are ready go to send a mail. Let’s see End to End example to implement these three steps in the ongoing Java web application development tutorial.

Add mail dependency

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

Create a class under the utility package(EmailMessage.java)

EmailMessage is a bean class that contains all the getter and setter properties that we are going to user during the mail implementation.

package com.javawebapp.utility;

public class EmailMessage {

  private String to = null;
  private String from = null;
  private String cc = null;
  private String bcc = null;
  private String subject = null;
  private String message = null;
  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;
  }

}

Create another class in the utility package(EmailUtility.java)

The below code contains three steps that we need to implement to send a mail.

package com.javawebapp.utility;
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 = "Enter Email_Id";
     String sender_email_pass = "Enter Password";

       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) {
           
       } 
   }


}

CheckMail.java

package com.javawebapp.model;

import org.omg.CORBA.portable.ApplicationException;

import com.javawebapp.utility.EmailMessage;
import com.javawebapp.utility.EmailUtility;

public class CheckMail {
  
  public static void main(String[] args) {
    EmailMessage msg=new EmailMessage();
    msg.setTo("bhupendra.patidar42@gmail.com");
    msg.setMessage("Hii");
    try {
      EmailUtility.sendMail(msg);
    } catch (ApplicationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

}