Sending email through Java with SSL / TLS authentication
Last Updated :
22 Jul, 2021
The JavaMail API defines classes that represent the components of a mail system. JavaMail does not implement an email server, instead, it allows you to access an email server using a Java API. In order to test the code presented, you must have access to an email server. While the JavaMail API specification does not mandate support for specific protocols, JavaMail typically includes support for POP3, IMAP, and SMTP.
How does Email Work?
Prerequisite:
- Have access to an SMTP server. You must know the hostname, port number, and security settings for your SMTP server. Webmail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your username is often your full email address and not just the name that comes before the @ symbol.
- A Java EE IDE and Application Servers such as GlassFish or Oracle WebLogic Server. JavaMail can be downloaded as a library in a Java SE application but this tutorial assumes the use of a Java EE application server which would already include JavaMail.
There are the following three steps to send email using JavaMail. They are as follows:
Get the session object - javax.mail.Session class provides object of session, Session.getDefaultInstance() method and Session.getInstance() method.
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// mail username and password
properties.setProperty("mail.user", "user");
properties.setProperty("mail.password", "password$$");
Compose the message- javax.mail.Transport class provides method to send the message.
// javax.mail.internet.MimeMessage class is
// mostly used for abstraction.
MimeMessage message = new MimeMessage(session);
// header field of the header.
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("subject");
message.setText("Hello, aas is sending email ");
Send the message
Transport.send(message);
Following is the Send Mail in Java using SMTP without authentication full implementation in java-
Java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
public static void main(String[] args)
{
// change below lines accordingly
String to = "[email protected]";
String from = "[email protected]";
String host = "localhost"; // or IP address
// Get the session object
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object
Session session = Session.getDefaultInstance(properties);
// compose the message
try {
// javax.mail.internet.MimeMessage class
// is mostly used for abstraction.
MimeMessage message = new MimeMessage(session);
// header field of the header.
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("subject");
message.setText("Hello, aas is sending email ");
// Send message
Transport.send(message);
System.out.println("Yo it has been sent..");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Output
Yo it has been sent...
The program is simple to understand and works well, but in real life, most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So, we will now see how to create a Session object for these authentication protocols. For TLS & SSL you can know the port in which the mail server running those services. We will provide you code taking Gmail into consideration. Following is the Send Mail in Java using SMTP with TLS authentication full implementation in java-
Java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
public static void main(String[] args) {
// change accordingly
final String username = "[email protected]";
// change accordingly
final String password = "password";
// or IP address
final String host = "localhost";
// Get system properties
Properties props = new Properties();
// enable authentication
props.put("mail.smtp.auth", "true");
// enable STARTTLS
props.put("mail.smtp.starttls.enable", "true");
// Setup mail server
props.put("mail.smtp.host", "smtp.gmail.com");
// TLS Port
props.put("mail.smtp.port", "587");
// creating Session instance referenced to
// Authenticator object to pass in
// Session.getInstance argument
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});
try {
// compose the message
// javax.mail.internet.MimeMessage class is
// mostly used for abstraction.
Message message = new MimeMessage(session);
// header field of the header.
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("hello");
message.setText("Yo it has been sent");
Transport.send(message); //send Message
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Following is the Send Mail in Java using SMTP with SSL authentication full implementation in java-
Java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
public static void main(String[] args)
{
// change accordingly
String to = "[email protected]";
// change accordingly
String from = "[email protected]";
// or IP address
String host = "localhost";
// mail id
final String username = "[email protected]"
// correct password for gmail id
final String password = "mypassword";
System.out.println("TLSEmail Start");
// Get the session object
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// SSL Port
properties.put("mail.smtp.port", "465");
// enable authentication
properties.put("mail.smtp.auth", "true");
// SSL Factory
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
// creating Session instance referenced to
// Authenticator object to pass in
// Session.getInstance argument
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
// override the getPasswordAuthentication
// method
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication("username",
"password");
}
});
}
//compose the message
try {
// javax.mail.internet.MimeMessage class is mostly
// used for abstraction.
MimeMessage message = new MimeMessage(session);
// header field of the header.
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("subject");
message.setText("Hello, aas is sending email ");
// Send message
Transport.send(message);
System.out.println("Yo it has been sent..");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Multiple clients we can have the following changes in the above code
Java
// This is an array of e-mail ID. You would
// need to use InternetAddress() method
// while specifying email IDs
void addRecipients(Message.RecipientType type,
Address[] addresses)
Similar Reads
Authentication with API Key in Java
Usually, in a web application, we will log in by using a username(email id/login name) with a password. Securely we can do the same by using an APIKey as well. Let us see what is an APIKey. The API key is a unique identifier that authenticates requests and if several users are there, their username
5 min read
OAuth2 Authentication with Spring and Github
OAuth2 is a secure way to allow users to log in to your application using third-party providers like GitHub. Instead of creating a custom login system, we can use GitHubâs authentication to verify users and grant access.Working of OAuth2Imagine a user wants to log in to your app using GitHub. When t
2 min read
Spring Security - Basic Authentication
Spring Security is a framework that allows a programmer to use JEE (Java Enterprise Edition) components to set security limitations on Spring Framework-based web applications. As a core part of the Spring ecosystem, itâs a library that can be utilized and customized to suit the demands of the progra
6 min read
Servlet - Authentication Filter
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Authentication Filter In Servlets Authentication may
2 min read
Authentication in Spring Security
In Spring Security, âauthenticationâ is the process of confirming that a user is who they say they are and that they have the right credentials to log in to a protected resource or to perform a privileged action in an application. Spring Security helps you set up different authentication methods, li
13 min read
How to Implement Simple Authentication in Spring Boot?
In this article, we will learn how to set up and configure Basic Authentication with Spring. Authentication is one of the major steps in any kind of security. Spring provides dependencies i.e. Spring Security that helps to establish the Authentication on the API. There are so many ways to add Authen
4 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the Spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. In this article, we are going to learn how to implement JWT authenti
8 min read
Spring Security - JDBC Authentication
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or Protocol) for Java applications to communicate with various databases. It provides the language with Java datab
8 min read
JWT Authentication In Node.js
In modern web development, ensuring secure and efficient user authentication is paramount. JSON Web Tokens (JWT) offer a robust solution for token-based authentication, enabling secure transmission of user information between parties. This article provides a step-by-step approach to implementing JWT
3 min read
Spring Security - Form-Based Authentication
Form-Based Authentication in Spring Security provides a secure way to authenticate users using a custom login form instead of the default security prompt. It allows better control over authentication flow, user experience, and security configurations. Key Features:Customizable login and logout mecha
5 min read