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

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:

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>
</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("mail.host", "smtp.gmail.com");

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

        		//Add Recipient EMail ID
        		//E.g. xxxx@gmail.com,xxxx@yahoo.co.in
        		generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("username@gmail.com"));

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

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

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

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

       		//Close the session
      		transport.close();
    	}
}

[ YOU MAY ALSO LIKE ]

Leave a Reply