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

 

Email JavaMail API

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

  • mail.jar
  • activation.jar
Sending Email JavaMail API

 

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

 

Previous
Next

One Response

  1. Pooja Kalpesh Rajput May 4, 2018