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:
-
- Create a new Maven QuickStartProject “JavaEmail” and create a package for our src files “com.javainterviewpoint“
- 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>
- Create the Java classes SendEmailGmailTLS.java and SendEmailGmailSSL.java under com.javainterviewpoint folder.
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 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(); } } }
Leave a Reply