How to send mail using servlet

To send an email using a servlet, you can use the JavaMail API, which is a part of the Java Standard Edition (SE) platform. Here's a step-by-step guide to help you get started:

Prerequisites:

  1. You need to have a Java Development Kit (JDK) installed on your system.
  2. You need to have a servlet container like Apache Tomcat or Jetty to deploy your servlet.
  3. You need to have the JavaMail API jar file (javax.mail.jar) in your project's classpath.

Step 1: Add the JavaMail API jar file to your project

Download the JavaMail API jar file from the official website and add it to your project's classpath. You can also use a Maven dependency or Gradle dependency to include the JavaMail API in your project.

Step 2: Create a servlet

Create a new Java class that extends the HttpServlet class. This class will handle the email sending functionality.

Here's an example servlet code:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;

public class EmailServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the email details from the request
        String toEmail = request.getParameter("toEmail");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");

        // Create a new MimeMessage object
        MimeMessage msg = new MimeMessage(session);

        // Set the sender's email address
        msg.setFrom(new InternetAddress("[email protected]"));

        // Set the recipient's email address
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));

        // Set the subject
        msg.setSubject(subject);

        // Set the message body
        msg.setText(message);

        // Send the email
        Transport.send(msg);

        // Response to the client
        response.getWriter().println("Email sent successfully!");
    }
}

Step 3: Configure the JavaMail API

Create a session object that will be used to send the email. You can configure the session object to use a specific SMTP server, port, and authentication details.

Here's an example configuration:

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");

Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("[email protected]", "your-password");
            }
        });

Step 4: Deploy the servlet

Deploy the servlet to your servlet container (e.g., Apache Tomcat). You can do this by creating a web.xml file in the WEB-INF directory of your project and configuring the servlet mapping.

Here's an example web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>EmailServlet</servlet-name>
        <servlet-class>EmailServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>EmailServlet</servlet-name>
        <url-pattern>/email</url-pattern>
    </servlet-mapping>
</web-app>

Step 5: Test the servlet

Use a tool like Postman or cURL to send a POST request to the servlet with the email details (toEmail, subject, and message). The servlet should send the email successfully and return a response to the client.

That's it! You have successfully sent an email using a servlet.