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:

https://docs.oracle.com/javaee/7/api/javax/mail/package-summary.html

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
    • (“mail.smtp.host”, “smtp.gmail.com”)
    • // ‘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 = "xxxxx@gmail.com";
		final String senderPassword = "xxxxx";
		
		// Valid email id for reciepent.
		String recieverID = "xxxxx@gmail.com";
		
       // 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("mail.smtp.host", "smtp.gmail.com"); 
		// '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();
			multipart.addBodyPart(messageBodyPart);
			
			// Once all the subparts of the body added to the Multipart object
			// Use setContent method to pass as argument.
			message.setContent(multipart);
			
               // Step #7
			// Transport is a class which provides send() method to send email contains above message.
			Transport.send(message);
			System.out.println("Automation email report has been sent to all recipients");
		} catch (Exception e) {
			System.out.println("Error sending email " + e.getMessage());
			System.out.println(e.toString());
		}
	}
}

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.


800total visits,3visits today

Leave a Reply

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