Send EMail (GMail/Google Mail) using Java Mail API

           This article details on how to send mail (GMail/Google Mail) using Java API. Google by default does not allow any 3rd party applications to access GMail account from any programming language. Google provide an option to turn on Less secure apps to get access from external applications. The following program works if Less secure apps is turned on. Also make sure to disable or shutdown anti-virus or firewall program if it is running. In my case, Avast anti-virus was blocking my application when sending the mail.

Maven Dependencies:


           Add the above MAVAN dependencies to the POM file or add the JARs specified in the POM to the classpath.

Sample Java Program:

package testpackage;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GMailTest {
    	public static void main(String args[]) throws AddressException, MessagingException     {

        		//Mail Server Properties
        		Properties mailServerProperties = new Properties();
        		mailServerProperties.put("mail.smtp.port", "587");
        		mailServerProperties.put("mail.smtp.auth", "true");
        		mailServerProperties.put("mail.smtp.starttls.enable", "true");
        		mailServerProperties.put("", "");

        		// Setup Session
        		Session session = Session.getDefaultInstance(mailServerProperties, null);
        		MimeMessage generateMailMessage = new MimeMessage(session);

        		//Add Recipient EMail ID
        		generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(""));

        		generateMailMessage.setSubject("Technology Source");
        		String emailBody = "Mail from Technology Source (";
        		generateMailMessage.setContent(emailBody, "text/html");

        		//Get Session
        		Transport transport = session.getTransport("smtp");

	        //GMail username with or without
        		//username or
        		transport.connect("GMail Username", "Password");

        		//Send the Mail
        		transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());

       		//Close the session

Leave a Reply