E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That's the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like - communication, Multi-Factor Authentication, etc. Working with mailing service within servlet requires - SMTP server(local/remote) and the two following APIs.
- Java Mail API (JMA) - javax.mail.jar
- JavaBeans Activation Framework API (JAF) - activation.jar
Pre-requisites:
- If you use the Gmail SMTP server, the Sign-in attempt can be blocked due to
- 2-step verification is turned on,
- Less secure app access is turned off.
- You can either change the google account settings or use Sign-in with Google / Google generated App code.
- Understanding mailing service protocols
Protocols
| Description
|
---|
SMTP
| Simple Mail Transfer Protocol is used to send a message from one mail server to another. |
POP
| Post Office Protocol is used to retrieve messages from a mail server. This protocol transfers all messages from the mail server to the mail client. |
IMAP
| Internet Message Access Protocol is used by web-based mail services such as Gmail and Yahoo. This protocol allows a web browser to read messages that are stored on the mail server. |
MIME
| The Multipurpose Internet Mail Extension type specifies the type of content that can be sent as a message or attachment. |
Understanding the Working of Email
Life-Cycle of Email
Steps to associate Java Mail API:
- Download the javax.mail.jar file.
- Copy the javax.mail.jar file to the application's WEB-INF\lib directory.
- Add the javax.mail.jar file to the classpath for your application.
Steps to associate JavaBeans Activation Framework API:
- Download the ZIP file and extract the files.
- Copy the activation.jar file to the application's WEB-INF\lib directory.
- Add the activation.jar file to the classpath for your application.
Note: The JavaBeans Activation Framework API is included with Java SE 6. As a result, if you're using Java SE 6 or later, you don't need to install this API.
Web-Application (Servlet) Structure:
Association of files in Servlet Web-Application
1] web.xml (configuration)
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html/web-app_3_1.xsd">
<servlet>
<servlet-name>Email</servlet-name>
<servlet-class>mail.Servlet.Email</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Email</servlet-name>
<url-pattern>/Email</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
2] index.html (Entering Details)
HTML
<!DOCTYPE html>
<html>
<head>
<title>GeeksforGeeks</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Email" method="post">
<div align="center"> <h1>Enter the Credentials: </h1>
<input type="hidden" name="action" value="add">
<label for="sID">Sender ID :</label> <br>
<input id="sID" type="text" name="id"> <br>
<label for="sMail">Sender Email :</label> <br>
<input id="sMail" type="email" name="emailSender"> <br>
<label for="pw">Password :</label> <br>
<input id="pw" type="password" name="password"> <br>
<label for="rMail">Receiver Email :</label> <br>
<input id="rMail" type="email" name="emailReceiver"> <br>
<label for="sub">Subject :</label> <br>
<input id="sub" type="text" name="subject"> <br>
<label for="message">Message :</label> <br>
<input id="message" type="text" name="message"><br>
<input type="submit" value="Send">
</div>
</form>
</body>
</html>
Output:
Fill details in output of Mail.java
3] Email.java (Servlet for handling details)
Java
package mail.Servlet;
import static mail.Servlet.Mail.sendMail;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Email extends HttpServlet {
protected void
processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String id, sender, receiver, password, subject,
message;
// check if directed url
String action = request.getParameter("action");
String url = "/index.html";
if (action == null) {
// directed to email interface
action = "join";
}
if (action.equals("join")) {
url = "/index.html";
}
if (action.equals("add")) {
// retrieve the entered credentials
id = request.getParameter("id");
sender = request.getParameter("emailSender");
receiver
= request.getParameter("emailReceiver");
password = request.getParameter("password");
subject = request.getParameter("subject");
message = request.getParameter("message");
// get and set String value of email status
request.setAttribute(
"message",
sendMail(id, receiver, sender, subject,
message, true, password));
// directed to page showing the status of email
url = "/confirmation.jsp";
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// Returns a short description of the servlet.
// @return a String containing servlet description
@Override public String getServletInfo()
{
return "Short description";
}
}
4] Mail.java (Helper class for creating and sending mail)
Essential classes:
Packages
| Description
|
---|
java.util
| Contains Properties class that’s used to set the properties for the email session. |
javax.mail
| Contains Session, Message, Address, Transport, MessagingException classes to send messages. |
javax.mail.internet | Contains MimeMessage and InternetAddress classes to send Email messages over the internet. |
Create and Send an Email Message:
Creating Mail Session:
- You have to create a mail session to create and send an email message.
- Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.
- You at the least need to specify SMTP host property - use the 'localhost' keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).
- You can use other properties as well to configure mail sessions.
- Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class.
Common Properties
| Description
|
---|
mail.transport.protocol | Specifies the protocol that’s used for the session. |
mail.smtp.host
| Specifies the host computer for the SMTP server. |
mail.smtp.port
| Specifies the port that the SMTP server is using. |
mail.smtp.auth
| Specifies whether authentication is required to log in to the SMTP server. |
mail.smtp.quitwait
| Set to false to prevent an SSLException on an attempt to connect to the Gmail SMTP server. |
// local SMTP server - Default
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
// local SMTP server - Configure
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
// remote SMTP server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.auth","true");
props.put("mail.smtps.quitwait","false");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Creating Message:
- To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.
- You can set the subject, body, and addresses for the message.
- If the body is other than plain text, use the setContent() method to change the MIME type of message.
Message message = new MimeMessage(session);
message.setSubject("Test");
// automatically sets to text/plain
message.setText("Test Successful");
message.setContent("<h1>Test Successful<h1>", "text/html");
Note: All of the Message methods used above throws javax.mail.MessagingException.
// add attachments within email
// create 1'st part of body
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("Body Message");
Multipart multiPart = new MimeMultipart();
// wrap up 1'st part
multiPart.addBodyPart(bodyPart);
// create 2'nd part of body
bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("Filename.txt");
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName("Filename.txt");
// wrap up 2'nd part.
multiPart.addBodyPart(bodyPart);
// adds wrapped parts in message
message.setContent(multiPart);
Addressing a message:
- Create an object of InternetAddress (Sub-class of Address class).
- The first argument specifies the email address.
- You can add a second argument to associate an ID or email address to be displayed.
- To set FROM address. use setFrom(Address add) method of the MimeMessage object.
- To set TO, CC (carbon copy), BCC (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.
- For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object.
// set sender
Address fromAdd = new InternetAddress("[email protected]", "from ID");
message.setFrom(fromAdd);
// set recipient
Address toAdd = new InternetAddress("[email protected]");
message.setRecipient(Message.RecipientType.TO, toAdd);
message.setRecipient(Message.RecipientType.CC, toAdd);
message.setRecipient(Message.RecipientType.BCC, toAdd);
// set recipients
message.setRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress("[email protected]"),new InternetAddress("[email protected]")});
// add recipients
Address toAdd1 = new InternetAddress("[email protected]");
message.addRecipient(Message.RecipientType.TO, toAdd1);
Note: When you send a carbon copy, the CC addresses appear in the message. When you send a blind carbon copy, the BCC address doesn't appear in the message. If you use the two-argument constructor of InternetAddress, it throws the java.io.UnsupportedEncoding Exception.
Sending a message:
If the SMTP doesn't require authentication, you can use the static send(Message msg) method of the Transport class to send a message.
Transport.send(message);
- If the SMTP requires authentication, you can use the getTransport() method of the session object.
- Then you can use connect method - public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.
- Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.
- You need to close the connection using the close() method if not used try-with-resources block.
Transport transport = session.getTransport();
transport.connect("email-id", "password");
transport.sendMessage("message", message.getAllRecipients());
transport.close();
Note: If the SMTP host is incorrect, the - static void send(Message msg) method throws SendFailedException.
Java
package mail.Servlet;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
public static String
sendMail(String id, String to, String from,
String subject, String body, boolean content,
String password)
{
String status = null;
try {
// acquire a secure SMTPs session
Properties pros = new Properties();
pros.put("mail.transport.protocol", "smtps");
pros.put("mail.smtps.host", "smtp.gmail.com");
pros.put("mail.smtps.port", 465);
pros.put("mail.smtps.auth", "true");
pros.put("mail.smtps.quitwait", "false");
Session session
= Session.getDefaultInstance(pros);
session.setDebug(true);
// Wrap a message in session
Message message = new MimeMessage(session);
message.setSubject(subject);
if (content) {
message.setContent(body, "text/html");
}
else {
message.setText(body);
}
// specify E-mail address of Sender and Receiver
Address sender = new InternetAddress(from, id);
Address receiver = new InternetAddress(to);
message.setFrom(sender);
message.setRecipient(Message.RecipientType.TO,
receiver);
// sending an E-mail
try (Transport tt = session.getTransport()) {
// acqruiring a connection to remote server
tt.connect(from, password);
tt.sendMessage(message,
message.getAllRecipients());
status = "E-Mail Sent Successfully";
}
}
catch (MessagingException e) {
status = e.toString();
}
catch (UnsupportedEncodingException e) {
status = e.toString();
}
// return the status of email
return status;
}
}
5] confirmation.jsp (Check the status of email)
HTML
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GeeksforGeeks</title>
</head>
<body>
<h3 align="center">Status of E-Mail : </h3>
<h1 align="center">${requestScope.message}</h1>
</body>
</html>
Output:
Mail Status after life-cycle
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Programming BasicsJava is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easier
8 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods, or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion of memory dedicated
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read