Categories: Servlet

Sending email through JavaMail API in Servlet

In this example we will see how to send email in Servlet application. JavaMail API that provides all classes require for sending an email. JavaMail API encapsulate two important package javax.mail and javax.mail.internet. These packages provides classes that can be used to send and receive simple emails. You simply need an Internet connection to send email using this simple Application.
  • index.html will get the input from user
  • MailApp.java servlet file will control the request and response. It will invoke send() of SendMail class that we have created to send the mail.
  • SendMail.java, a java class that contains method to send mail.

index.html

<form action="mail" method="post">
 To:<input type="text" name="to"  /><br/>
 Subject:<input type="text" name="subject"  /><br/>
 Message:<input type="text" name="message"  /><br/>
 Your Email id:<input type="text" name="user" ><br/>
 Password<;input type="password" name="pass"   /><br/>
<input type="submit" value="send" />
 </form>

 

MailApp.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class MailApp extends HttpServlet {

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message =  request.getParameter("message");
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        SendMail.send(to,subject, message, user, pass);
        out.println("Mail send successfully");
        
    }   
}

SendMail.java

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;


public class SendMail 
    
   {
    
    public static void send(String to, String sub, 
                         String msg, final String user,final String pass)
    {
     
     //create an instance of Properties Class     
     Properties props = new Properties();
     
     /* Specifies the IP address of your default mail server
     for e.g if you are using gmail server as an email sever
     you will pass smtp.gmail.com as value of mail.smtp host. As shown here in the 
    coding. Change accordingly, if your email id is not an gmail id*/
     props.put("mail.smtp.host", "smtp.gmail.com");
     
     props.put("mail.smtp.port", "587"); //this is optional 
     props.put("mail.smtp.auth", "true");
     props.put("mail.smtp.starttls.enable", "true");
     

     
     /*Pass Properties object(props) and Authenticator object   
           for authentication to Session instance */

    Session session = Session.getInstance(props,
                        new javax.mail.Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(user,pass);
   }
});
    
 try
 {
 
 /* Create an instance of MimeMessage, 
 it accept MIME types and headers */
 
 MimeMessage message = new MimeMessage(session);
 message.setFrom(new InternetAddress(user));
 message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
 message.setSubject(sub);
 message.setText(msg);

 /* Transport class is used to deliver the message to the recipients */
 Transport.send(message);
 
 
 }catch(Exception e)
 {
     e.printStackTrace();
 }
    }
    
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
    <servlet>
        <servlet-name>mail</servlet-name>
        <servlet-class>MailApp</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>mail</servlet-name>
        <url-pattern>/mail</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago