Servlet Send Email

Sending an email from a Servlet can be done using the JavaMail API. Let's go through a tutorial on how to create a servlet that sends an email.

Step 1: Add JavaMail dependency

The first step is to add the JavaMail API to your project. If you're using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Step 2: Create a new dynamic web project

Create a new dynamic web project in your IDE.

Step 3: Create a new Servlet

Create a new servlet in your project. We'll name it "SendEmailServlet" for this tutorial.

Step 4: Write the Servlet code

In the created servlet, write the following code:

package com.example;

import java.io.IOException;
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;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SendEmailServlet")
public class SendEmailServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Recipient's email ID needs to be mentioned.
        String to = "recipient@example.com";

        // Sender's email ID needs to be mentioned
        String from = "sender@example.com";

        // Assuming you are sending email from through gmails smtp
        String host = "smtp.gmail.com";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "465");
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.auth", "true");

        // Get the Session object.// and pass username and password
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication("username", "password");

            }

        });

        // Used to debug SMTP issues
        session.setDebug(true);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("This is the Subject Line!");

            // Now set the actual message
            message.setText("This is actual message");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

This servlet sends an email when it receives a GET request. Replace the "username" and "password" values with the username and password of the email account you are using to send email. If you're using a Gmail account, you'll need to generate an app password to use here.

Step 5: Running the Servlet

Run the servlet on your server.

You should now be able to send an email by accessing your servlet. For example, if the server is running on your local machine, you can access your servlet at `http://localhost:8080/YourProjectName/SendEmailServlet`.

Note: In a real-world application, you wouldn't hard-code the email details like this. Instead, you'd probably get them from a configuration file or environment variables, and you'd likely have a form on your site where users could enter the email content.

Remember that sending email can fail for a variety of reasons, such as if the SMTP server is down, if the credentials are incorrect, or if the recipient's email address doesn't exist. Your code should be prepared to handle these cases.

Additionally, most email providers have restrictions on how many emails you can send in a certain period of time, to prevent spam. If you're sending a lot of emails, you might need to use a dedicated email sending service.

  1. Sending emails from Java Servlets: Sending emails from Servlets involves using the JavaMail API to connect to an SMTP server and send email messages.

  2. JavaMail API in Servlets: The JavaMail API provides classes for sending and receiving email messages. Include the necessary JAR files in your project.

  3. Servlet email sending example code: Use the JavaMail API to send emails from a Servlet.

    // Create a Session
    Session session = Session.getDefaultInstance(properties);
    
    // Create a message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("sender@example.com"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
    message.setSubject("Subject");
    message.setText("Body");
    
    // Send the message
    Transport.send(message);
    
  4. Handling attachments in Servlet email: Attach files to your email messages using the MimeBodyPart class.

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.attachFile(new File("attachment.pdf"));
    
  5. Sending HTML emails from Servlet: Send HTML-formatted emails by setting the content type to "text/html".

    message.setContent("<html><body><h1>Hello, World!</h1></body></html>", "text/html");