Categories: JavaMail

Sending Email JavaMail API

Here is an example to send a simple email. Here we have used SMPT server via which emails are sent to our destination email address. There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.

Sending Email JavaMail API

You can use one of the following techniques to get the SMTP server:

  • Install and use any SMTP server such as Postcast server, Apache James server, gmail server etc. (or)
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.dineshonjava.com (or)
  • Use the SMTP Server provided by other companies e.g. gmail etc.

Here, we are going to learn above three approaches to send email using javamail API. But we should learn the basic steps to send email from java application.

To send a simple email steps followed are:

  1. Get the session object that stores all the information of host like host name, username, password etc.
  2. compose the message
  3. send the message

Get the session object

The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use anyone method to get the session object.

Examples of these methods are as follows:

1.Syntax of getDefaultInstance() method
There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.

public static Session getDefaultInstance(Properties props)  
public static Session getDefaultInstance(Properties props,Authenticator auth)  

Example of getDefaultInstance() method

Properties properties=new Properties();  
//fill all the informations like host name etc.  
Session session=Session.getDefaultInstance(properties,null); 

2.Syntax of getInstance() method
There are two methods to get the session object by using the getInstance() method. It returns the new session.

public static Session getInstance(Properties props)  
public static Session getInstance(Properties props,Authenticator auth)  

Example of getDefaultInstance() method

Properties properties=new Properties();  
//fill all the informations like host name etc.  
Session session=Session.getInstance(properties,null);

Compose the message

The javax.mail.Message class provides methods to compose the message. But it is an abstract class so its subclass javax.mail.internet.MimeMessage class is mostly used.

To create the message, you need to pass session object in MimeMessage class constructor.

For example:

MimeMessage message=new MimeMessage(session); 

Now message object has been created but to store information in this object MimeMessage class provides many methods. Let’s see methods provided by the MimeMessage class:

Commonly used methods of MimeMessage class

  • public void setFrom(Address address): is used to set the from header field.
  • public void addRecipients(Message.RecipientType type, String addresses): is used to add the given address to the recipient type.
  • public void setSubject(String subject): is used to set the subject header field.
  • public void setText(String textmessage) is used to set the text as the message content using text/plain MIME type.

Example to compose the message:

MimeMessage message=new MimeMessage(session);  
message.setFrom(new InternetAddress("dineshonjava@gmail.com"));  
message.addRecipient(Message.RecipientType.To,   
new InternetAddress("admin@dineshonjava.com"));  
message.setHeader("Wecome to JAVAMail Tutorial");  
message.setText("Hi Users, This is java mail tutorial...");

Send the message

The javax.mail.Transport class provides method to send the message.

Commonly used methods of Transport class

  • public static void send(Message message): is used send the message.
  • public static void send(Message message, Address[] address): is used send the message to the given addresses.

Example to send the message:

Transport.send(message); 

Sending Simple Email Example-

Create Java Class

Create a java class file SendEmail, the contents of which are as follows:

JavaMail – GMail via TLS

Send an Email via Gmail SMTP server using TLS connection.

import java.util.Properties;

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

public class SendEmail {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "dinesh.mca.jss@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "dineshonjava@gmail.com";
      final String username = "dineshonjava";//change accordingly
      final String password = "*****";//change accordingly

      // Assuming you are sending email through relay.jangosmtp.net
      String host = "smtp.gmail.com";

        Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

      // Get the Session object.
      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
    }
         });

      try {
    // Create a default MimeMessage object.
    Message message = new MimeMessage(session);
 
    // Set From: header field of the header.
    message.setFrom(new InternetAddress(from));
 
    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO,
               InternetAddress.parse(to));
 
    // Set Subject: header field
    message.setSubject("Testing Subject");
 
    // Now set the actual message
    message.setText("Hello, this is sample for to check send " +
  "email using JavaMailAPI ");

    // Send message
    Transport.send(message);

    System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

 

For sending the email using JavaMail API, you need to load the two jar files:

  • mail.jar
  • activation.jar

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago