Servlet Send Email

Sending an email using a Servlet is very simple, but first you must install on your computerJavaMail APIandJava Activation Framework)JAF)。

  • You can download the latest version from the Java websiteJavaMailopen the webpage, and on the right side there is aDownloadslink, click it to download.
  • From the Java website, you can download the latest version ofJAF (version 1.1.1)。

You can also use the download link provided by this site:

  • JavaMail mail.jar 1.4.5
  • JAF (version 1.1.1) activation.jar

Download and extract these files. In the newly created top-level directory, you will find some jar files for these two applications. You need to addmail.jarandactivation.jarthe files to your CLASSPATH.

Send a Simple Email

The following example will send a simple email from your computer. Here it is assumed that yourlocalhostis connected to the internet and supports sending email. Also ensure that all the jar files of the Java Email API package and the JAF package are available in the CLASSPATH.

// 文件名 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
  {
      // 收件人的电子邮件 ID
      String to = "abcd@gmail.com";
 
      // 发件人的电子邮件 ID
      String from = "web@gmail.com";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

      try{
         // 创建一个默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
         // 设置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // 设置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
         // 设置 Subject: header field
         message.setSubject("This is the Subject Line!");
         // 现在设置实际消息
         message.setText("This is actual message");
         // 发送消息
         Transport.send(message);
         String title = "发送电子邮件";
         String res = "成功发送消息...";
         String docType = "<!DOCTYPE html> \n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#F0F0F0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
} 

Now let us compile the above Servlet and create the following entry in the 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 IDabcd@gmail.com, and will display the response shown below:

Send Email

Message sent successfully...

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

Below is a description of the parameters:

  • type:This will be set to TO, CC, or BCC. Here, CC stands for carbon copy, and BCC stands for blind carbon copy. For exampleMessage.RecipientType.TO。
  • addresses:This is an array of email IDs. When specifying email IDs, you need to use the InternetAddress() method.

Send an HTML Email

The following example will send an HTML-formatted email from your computer. Here it is assumed that yourlocalhostis connected to the internet and supports sending email. Also ensure that all the jar files of the Java Email API package and the JAF package 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 to "text/html", which is used to specify that the HTML content is included in the message.

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

// 文件名 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
  {
      // 收件人的电子邮件 ID
      String to = "abcd@gmail.com";
 
      // 发件人的电子邮件 ID
      String from = "web@gmail.com";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

      try{
         // 创建一个默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
         // 设置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // 设置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
         // 设置 Subject: header field
         message.setSubject("This is the Subject Line!");

         // 设置实际的 HTML 消息,内容大小不限
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
         // 发送消息
         Transport.send(message);
         String title = "发送电子邮件";
         String res = "成功发送消息...";
         String docType = "<!DOCTYPE html> \n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#F0F0F0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
} 

Compile and run the above Servlet, and send the HTML message to the given email ID.

Send Attachments in an Email

The following example will send an email with an attachment from your computer. Here it is assumed that yourlocalhostis connected to the internet and supports sending email. Also ensure that all the jar files of the Java Email API package and the JAF package are available in the CLASSPATH.

// 文件名 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
  {
      // 收件人的电子邮件 ID
      String to = "abcd@gmail.com";
 
      // 发件人的电子邮件 ID
      String from = "web@gmail.com";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

       try{
         // 创建一个默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
 
         // 设置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
 
         // 设置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // 设置 Subject: header field
         message.setSubject("This is the Subject Line!");
 
         // 创建消息部分 
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 填写消息
         messageBodyPart.setText("This is message body");
         
         // 创建一个多部分消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 第二部分是附件
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整的消息部分
         message.setContent(multipart );
 
         // 发送消息
         Transport.send(message);
         String title = "发送电子邮件";
         String res = "成功发送电子邮件...";
         String docType = "<!DOCTYPE html> \n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#F0F0F0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
} 

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

User Authentication Section

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

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

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

Other Extensions