Easy Tutorial
❮ Servlet First Example Servlet Intro ❯

Servlet Sending Email

Sending an email using a Servlet is quite simple, but first, you must install the JavaMail API and the Java Activation Framework (JAF) on your computer.

Alternatively, you can use the download links provided on this site:

Download and unzip these files. In the newly created top-level directory, you will find some JAR files for these applications. You need to add the mail.jar and activation.jar files to your CLASSPATH.

Sending a Simple Email

The following example will send a simple email from your computer. Here, it is assumed that your localhost is connected to the internet and supports sending emails. Also, ensure that all the JAR files for the Java Email API and JAF packages are available in your CLASSPATH.

// File name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail extends HttpServlet {

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException {
      // Recipient's email ID
      String to = "[email protected]";

      // Sender's email ID
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // 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);

      // Set response content type
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

      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 the actual message");
         // Send message
         Transport.send(message);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
                          "transitional//en\">\n";
         out.println(docType +
                     "<html>\n" +
                     "<head><title>" + title + "</title></head>\n" +
                     "&lt;body bgcolor=\"#f0f0f0\">\n" +
                     "&lt;h1 align=\"center\">" + title + "</h1>\n" +
                     "&lt;p align=\"center\">" + res + "</p>\n" +
                     "</body></html>");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
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);
String title = "Send Email";
String res = "Successfully sent message...";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"&lt;body bgcolor=\"#f0f0f0\">\n" +
"&lt;h1 align=\"center\">" + title + "</h1>\n" +
"&lt;p align=\"center\">" + res + "</p>\n" +
"</body></html>");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

Now let's compile the above Servlet and create the following entry in web.xml file:

....
<servlet>
<servlet-name>SendEmail</servlet-name>
<servlet-class>SendEmail</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SendEmail</servlet-name>
<url-pattern>/SendEmail</url-pattern>
</servlet-mapping>
....

Now call this Servlet by accessing the URL http://localhost:8080/SendEmail. This will send an email to the given email ID [email protected] and display the following response:

| Send Email Successfully sent message... |

If you want to send an email to multiple recipients, then use the following method to specify multiple email IDs:

void addRecipients(Message.RecipientType type, 
                   Address[] addresses)
throws MessagingException

Here is the description of the parameters:

Sending an HTML Email

The following example will send an HTML formatted email from your computer. Here it is assumed that your localhost is connected to the internet and capable of sending email. Also make sure all the jar files for Java Email API and JAF are available in the CLASSPATH.

This example is very similar to the previous one, but here we use the setContent() method to set the second parameter as "text/html" which indicates that the HTML content is included in the message.

Using this example, you can send unlimited size of HTML content.

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient's email ID String to = "[email protected]";

// Sender's email ID
String from = "[email protected]";

// Assuming you are sending email from localhost
String host = "localhost";

// 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);

// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

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!");

    // Set the actual HTML message, content size unrestricted
    message.setContent("<h1>This is actual message</h1>",
                       "text/html");
    // Send message
    Transport.send(message);
    String title = "Send Email";
    String res = "Sent message successfully...";
    String docType = "<!DOCTYPE html> \n";
    out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "&lt;body bgcolor=\"#f0f0f0\">\n" +
                "&lt;h1 align=\"center\">" + title + "</h1>\n" +
                "&lt;p align=\"center\">" + res + "</p>\n" +
                "</body></html>");
} catch (MessagingException mex) {
    mex.printStackTrace();
}

}


Compile and run the above Servlet to send an HTML message to the specified email ID.

## Sending Attachments in Email

The following example sends an email with an attachment from your computer. It assumes that your **localhost** is connected to the internet and supports sending emails. Ensure that all the jar files for the Java Email API and JAF are available in the CLASSPATH.

// File name SendEmail.java import java.io.*;

import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail extends HttpServlet {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, IOException {
        // Recipient's email ID
        String to = "[email protected]";

        // Sender's email ID
        String from = "[email protected]";

        // Assuming you are sending email from localhost
        String host = "localhost";

        // 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);

        // Set response content type
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        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!");

            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();

            // Fill the message
            messageBodyPart.setText("This is message body");

            // Create a multipar message
            Multipart multipart = new MimeMultipart();

            // Set text message part
            multipart.addBodyPart(messageBodyPart);

            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            String filename = "file.txt";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);

            // Send the complete message parts
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            String title = "Send Email";
            String res = "Sent message successfully....";
            String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
            out.println(docType +
                    "<html>\n" +
                    "<head><title>" + title + "</title></head>\n" +
                    "&lt;body bgcolor=\"#f0f0f0\">\n" +
                    "&lt;h1 align=\"center\">" + title + "</h1>\n" +
                    "&lt;p align=\"center\">" + res + "</p>\n" +
                    "</body></html>");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
message.setContent(multipart);

// Send message
Transport.send(message);
String title = "Send Email";
String res = "Email sent successfully...";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"&lt;body bgcolor=\"#f0f0f0\">\n" +
"&lt;h1 align=\"center\">" + title + "</h1>\n" +
"&lt;p align=\"center\">" + res + "</p>\n" +
"</body></html>");
} catch (MessagingException mex) {
   mex.printStackTrace();
}
}
}

Compile and run the above Servlet to send a message with file attachments to the given email ID.

User Authentication Section

If you need to provide a user ID and password to the email server for authentication, you can set the properties as follows:

props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

The rest of the email sending mechanism remains the same as explained above. ```

❮ Servlet First Example Servlet Intro ❯