Example of sending email in Java using Gmail SMTP


This Java tutorial will explain how to send an email through Java program using Gmail server and JavaMail API. JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.

Required Library: In this example, you need to add below libraries in your project build path or set to the classpath.

  1. mail-1.4.jar
  2. javaee.jar
pom.xml
<dependencies>
	<dependency>
		<groupId>javax.mail</groupId>
		<artifactId>mail</artifactId>
		<version>1.4</version>
	</dependency>
	<dependency>
		<groupId>javax</groupId>
		<artifactId>javaee-api</artifactId>
		<version>7.0</version>
	</dependency>
</dependencies>

Note: You may face the javax.mail.AuthenticationFailedException exception. To resolve this check this tutorial javax.mail.AuthenticationFailedException

SendEmail.java
package org.websparrow;

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) {
		final String username = "[email protected]";
		final String password = "sender_email_password";

		// setting gmail smtp properties
		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");

		// check the authentication
		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("[email protected]"));

			// recipients email address
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));

			// add the Subject of email
			message.setSubject("JavaMail API Test");

			// message body
			message.setText("This is a test mail only");// message

			Transport.send(message);

			System.out.println("Email Sent Successfully");

		} catch (MessagingException e) {
			throw new RuntimeException(e);

		}
	}
}

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.