• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Send Email in Java using Gmail SMTP | TLS & SSL

November 12, 2018 by javainterviewpoint Leave a Comment

In this tutorial, we will learn How to Send Email in Java using Gmail SMTP, we will send email through gmail SMTP server by TLS (Transport Layer Security) and SSL (Secured Socket Layer).

Gmail SMTP Server Details

Gmail SMTP server details can be found in the below URL

https://support.google.com/a/answer/176600?hl=en

  • Gmail SMTP server – smtp.gmail.com
  • Port – 465 (SSL required)
  • Port – 587 (TLS required)

Folder Structure:

Send Email in Java using Gmail SMTP

    1. Create a new Maven QuickStartProject  “JavaEmail” and create a package for our src files “com.javainterviewpoint“
    2. Now add the following dependency in the POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainterviewpoint</groupId>
	<artifactId>JavaEmail</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>JavaEmail</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.6.0</version>
		</dependency>
	</dependencies>
</project>
  1. Create the Java classes SendEmailGmailTLS.java and SendEmailGmailSSL.java under  com.javainterviewpoint folder.

Other Posts which you may like …

  • Send Email Using Java
  • Write Excel File in Java using POI
  • Read Excel File in Java using POI
  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

Send Email in Java using Gmail SMTP with TLS [Transport Layer Security]

package com.javainterviewpoint;

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 SendEmailGmailTLS
{
    public static void main(String[] args)
    {
        // Gmail username
        final String username = "[email protected]";
        
        // Gmail password
        final String password = "password";
        
        // Receiver's email ID
        String receiver = "[email protected]";

        // Sender's email ID
        String sender = "[email protected]";

        // Sending email from gmail
        String host = "smtp.gmail.com";

        // Port of SMTP
        String port = "587";

        Properties properties = new Properties();

        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);

        // Create session object passing properties and authenticator instance
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

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

            // Set the Senders mail to From
            message.setFrom(new InternetAddress(sender));

            // Set the recipients email address
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));

            // Subject of the email
            message.setSubject("Java Send Email Gmail SMTP with TLS Authentication");

            // Body of the email
            message.setText("Welcome to Java Interviewpoint");

            // Send email.
            Transport.send(message);
            System.out.println("Mail sent successfully");
        } catch (MessagingException me)
        {
            me.printStackTrace();
        }
    }
}
  • Create variables for username, password, sender, receiver, host and port
  • Create a new instance of Properties class
Properties properties = new Properties();
  • Set the “mail.smtp.auth”, “mail.smtp.starttls.enable”, “mail.smtp.host” and “mail.smtp.port” to the properties instance using the put() method
 properties.put("mail.smtp.auth", "true");
 properties.put("mail.smtp.starttls.enable", "true");
 properties.put("mail.smtp.host", host);
 properties.put("mail.smtp.port", port);
  • Get the Java Mail Session instance passing the properties and authenticator instance to the getInstance() method. Override the getPasswordAuthentication() method of the Authenticator class
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
     }
});
  • Create a new MimeMessage object passing the session
MimeMessage message = new MimeMessage(session);
  • In order to set the sender and receivers email address we will be using the InternetAddress class.
  • Senders email address is set using the setFrom() method of the MimeMessage class, it takes up the InternetAddress class, we will pass the sender string to its constructor.
message.setFrom(new InternetAddress(sender));
  • The recipients email address is passed to the addRecipient() method. The recipient type can be Message.RecipientType.TO, Message.RecipientType.CC or Message.RecipientType.BCC
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
  • Set the subject with setSubject() and set the plaintext body content with setText()
message.setSubject("Java Send Email Example");
message.setText("Welcome to Java Interviewpoint");
  • Now call the send() method of the Transport class passing the message (MimeMessage) to send the mail
Transport.send(message);

Output:

Mail sent successfully

Note: 

Sometimes you might be getting the AuthenticationFailedException due to Gmail account protection

javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbuS
534-5.7.14 Mwz-nI3s8j_KKDBijmjPKtDKAdui2GnXx-5nc-DhIUULT89km-r_NQmTlPDnGm3usA2qOI
534-5.7.14 WMLQL0Girmh40h0-Tuf-IzBEHhs5EiYQn9MAiYOujSWkaOS56O2W0MAisD9ZXmvKw2bjl6
534-5.7.14 EJ18chNaQlRUnrlJjGg1WiLBKSl6pWhe9YlR1bPqIAdMNNrClEK5ORnw9SwjpE_FmBbjMJ
534-5.7.14 WRUheawjvlL2Qu3aKN9aQycwf0oEGDueoxdNBBxDfdSabQEiER> Please log in via
534-5.7.14 your web browser and then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/78754 c128-v6sm851117pfb.147 - gsmtp

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:950)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:861)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:766)
	at javax.mail.Service.connect(Service.java:388)
	at javax.mail.Service.connect(Service.java:246)
	at javax.mail.Service.connect(Service.java:195)
	at javax.mail.Transport.send0(Transport.java:254)
	at javax.mail.Transport.send(Transport.java:124)
	at com.javainterviewpoint.SendEmailGmailTLS.main(SendEmailGmailTLS.java:65)

Login your gmail account and go to url https://www.google.com/settings/security/lesssecureapps and turn on “Allow less secure apps”

Send Email in Java using Gmail SMTP 1

Send Email in Java using Gmail SMTP with SSL [Secure Socket Layer]

You just need to set the properties “mail.smtp.socketFactory.port”, “mail.smtp.socketFactory.class” to the properties instance using the put() method to send email in Java using Gmail with SSL authentication.

package com.javainterviewpoint;

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 SendEmailGmailSSL
{
    public static void main(String[] args)
    {
        // Gmail username
        final String username = "[email protected]";
        
        // Gmail password
        final String password = "passwrord";
        
        // Receiver's email ID
        String receiver = "[email protected]";

        // Sender's email ID
        String sender = "[email protected]";

        // Sending email from gmail
        String host = "smtp.gmail.com";

        // Port of SMTP
        String port = "465";

        Properties properties = new Properties();

        properties.put("mail.smtp.socketFactory.port", port);
        properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);

        // Create session object passing properties and authenticator instance
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

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

            // Set the Senders mail to From
            message.setFrom(new InternetAddress(sender));

            // Set the recipients email address
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));

            // Subject of the email
            message.setSubject("Java Send Email Gmail SMTP with SSL Authentication");

            // Body of the email
            message.setText("Welcome to Java Interviewpoint");

            // Send email.
            Transport.send(message);
            System.out.println("Mail sent successfully");
        } catch (MessagingException me)
        {
            me.printStackTrace();
        }
    }
}

    Download Source Code

Filed Under: Core Java, Java Tagged With: Gmail SMTP, Send Email, Send Email in Java using Gmail SMTP, SSL, TLS

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·