Basic Java – 19 || Sending Email using Java (Part-1).

After the successful execution of any program or tool, it is better to share status or report via sending email to the stakeholders.

Process of email configuration via Java.

This objective can be achieved by javax.mail package. javax is an extended version of Java which contains many sub-packages to give additional features to Java language. One of the most important features provided by javax is mailing functionality.

Package javax.mail provides all the common methods to handle mail using Java language. To learn more about javax.mail package go-through below link:

Download Jar Files



Sending Email using Java Step by Step

First of all, we have to gather below information to start the process of coding.

  1. Sender Information: Get a valid email user id and password who will send email
  2. Receiver Information: Valid email id who receives the email.
  3. Server Information: Get correct information about the mail server like hostname, port number, authentication status, etc.
  4. Mail information: The content which needs to be shared over the email like Subject, mail body, formatting, attachment, etc.

7 Steps in Java coding for Sending Email

  1. Store all the information of the sender and receiver in String objects.
    • String senderID
    • String senderPassword
    • String recieverID
  2. Store all the Server information in an object of Properties.
    • // Server name or service provider, used to send emails between servers
    • (“”, “”)
    • // ‘587’ is default port number for smtp
    • (“mail.smtp.port”, “587”)
    • // Make SMTP Authentication enabled
    • props.put(“mail.smtp.auth”, “true”);
    • // Convert an insecure connection to secure.
    • props.put(“mail.smtp.starttls.enable”, “true”);
  3. Create Session object to setup the connection with the Web Server and authenticate the sender’s email id and password.
    • Session.getInstance(props, new javax.mail.Authenticator()
    • getPasswordAuthentication()
    • return new PasswordAuthentication(senderID, senderPassword);
  4. Create mail content using Message Class and Session object.
    • Message message = new MimeMessage(session)
    • message.setRecipients(RecipientType, recieverID)
    • message.setSubject(String)
    • message.setContent(MultipartObject)
  5. Creating multiple instances of BodyPart Class, these instances will be added to the object of Multipart Class.
    • BodyPart messageBodyPart = new MimeBodyPart()
    • messageBodyPart.setText(“This is message body”);
  6. Creating an object of Multipart Class, Multipart is like a container which holds different part of the Mail body via multiple instances of the BodyPart. After that, we have to pass this object ‘multipart’ as an argument via setContent().
    • Multipart multipart = new MimeMultipart()
    • multipart.addBodyPart(messageBodyPart)
    • message.setContent(multipart)
  7. At the end we have to call send() of Transport class. Transport is an abstract class contains static method send().
    • Transport.send(message);

Code for sample Email

import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mailer {
	public static void main(String[] args) {
       // Step #1
		// Valid Credentials to send email.
		final String senderID = "";
		final String senderPassword = "xxxxx";
		// Valid email id for reciepent.
		String recieverID = "";
       // Step #2
                // Creating a configuration property file to pass as an argument for Session object.
		Properties props = new Properties();
	       // Server name or service provider, used to send emails between servers
		props.put("", ""); 
		// '587' is default port number for smtp
		props.put("mail.smtp.port", "587"); 
		// Make SMTP Authentication enabled 
		props.put("mail.smtp.auth", "true");
		// Convert an insecure connection to secure.
		props.put("mail.smtp.starttls.enable", "true");
        // Step #3
		// Session is a class to create a session object.
		// It provides access to protocol providers.
		// getInstance() method creates new session using the configuration mentioned in the above Properties file.
		// This property file used to supply information to connect with the Server to validate the credentials.
		Session session = Session.getInstance(props, new javax.mail.Authenticator() 
			// PasswordAuthentication is a call having getPasswordAuthentication() method
			// It get called automatically when authentication is required.
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(senderID, senderPassword);

		try {
          // Step #4
			// Creates an object of Message class using the exisitng Session object.
			// MimeMessage is a class which extends Message class.
			Message message = new MimeMessage(session);
			// setRecipients() method used to set Email for recipients.
			// IntenetAddress.parse() method used to validate the pattern of the standard email address.
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recieverID));
			// setSubject() method used to set Email Subject.
			message.setSubject("automation report");
            // Step #5
			// BodyPart class implements Part interface
			// It basically used to create multiple parts of the mail body.
			// First we have to create object of BodyPart class.
			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setText("This is message body");
			System.out.println("Body set...");
             // Step #6
			// Multipart is a class which works like a container and holds the different parts of the email.
			// We have to crate variou instances and add the same into the Multipart object.
			Multipart multipart = new MimeMultipart();
			// Once all the subparts of the body added to the Multipart object
			// Use setContent method to pass as argument.
               // Step #7
			// Transport is a class which provides send() method to send email contains above message.
			System.out.println("Automation email report has been sent to all recipients");
		} catch (Exception e) {
			System.out.println("Error sending email " + e.getMessage());

Note: There may be chances you get javax.mail.AuthenticationFailedException after executing the above code. This is because Google has an important security feature to protect your Gmail account from the other applications which seems insecure. By default, Google keeps this setting Off. Use the below link to get rid of this exception.

Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.