How To Send Email In Java Using Gmail SMTP

Hamza Farooq
3 min readOct 22, 2020

Sending Email is the most common requirement for most of the applications. Java provides Java Mail API, a platform and protocol-independent framework to build mail and messaging applications.
In this guide, you will get detailed steps on how to setup JavaMail in your Java Project and implement JavaMail API to build and send emails on SMTP protocol.

Suppose you have a maven project, then add the following dependencies in your pom.xml file.

<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>

Note: If you don't have maven project then you can download Java Mail API from maven repository and add it to your project build path.

Right-click on the package and create a new SendMail class

Creating a new java class

In your code, we would require to import the following packages and class. Here are some brief details about those packages and classes.

  • import java.util.Properties:
    The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.
  • import javax.mail.Message:
    This class models an email message. To send a message, a subclass of Message (e.g. MimeMessage) is instantiated, the attributes and content are filled in, and the message is sent using the Transport.send method.
  • import javax.mail.MessagingException:
    This is the base class for all exceptions thrown by the Messaging classes
  • import javax.mail.PasswordAuthentication:
    This class is simply a repository for a user name and a password.
  • import javax.mail.Session:
    The session class represents a mail session.
  • import javax.mail.Transport:
    This is an abstract class that models a message transport.
  • import javax.mail.internet.InternetAddress:
    This class represents an Internet email address using the syntax of RFC822
  • import javax.mail.internet.MimeMessage:
    This class represents a MIME style email message. It implements the Message abstract class and the MimePart interface.

Below is the full Java code to send emails using Gmail SMTP server, with the description of each line:

package com.sendemail;

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 SendMail {

public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "fromaddress@gmail.com";

// Sender's email ID needs to be mentioned
String from = "toaddress@gmail.com";

// Assuming you are sending email from through gmails smtp
String host = "smtp.gmail.com";

// Get system properties
Properties properties = System.getProperties();

// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");

// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("fromaddress@gmail.com", "password");

}

});

// Used to debug SMTP issues
session.setDebug(true);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

// Set Subject: header field
message.setSubject("This is the Subject Line!");

// Now set the actual message
message.setText("This is actual message");

System.out.println("sending...");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

If you want to send HTML content, replace message.setText(“This is actual message”) with below code:

// Send the actual HTML message.
message.setContent(
"<h1>This is actual message embedded in HTML tags</h1>", "text/html");

By default Gmail account is highly secured. When we use Gmail SMTP from a non-Gmail tool, email is blocked. To test in our local environment, make your Gmail account less secure as

  1. Login to Gmail.
  2. Access the URL as https://www.google.com/settings/security/lesssecureapps
  3. Select “Turn on”
Google Less Secure Apps Check

--

--

Hamza Farooq

Java Developer at Evamp & Saanga. Willing to learn and teach. Playing football to be in Shape.