Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet sends an e-mail message


May 15, 2021 Servlet


Table of contents


Servlet sends an e-mail message

It's easy to send an e-mail message using a servlet, but first you must install the JavaMail API and Java Activation Framework JAF on your computer.

Download and unzip these files, and in the newly created top-level directory, you'll find some jar files for both applications. You need to .jar mail .jar and activation files to your CLASSPATH.

Send a simple e-mail message

The following example sends a simple e-mail message from your computer. H ere is assuming that your local host is connected to the Internet and supports sending e-mail. Also ensure that all jar files for the Java Email API package and the JAF package are available in 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 = "[email protected]";
 
      // 发件人的电子邮件 ID
      String from = "[email protected]";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
   // 设置响应内容类型
      response.setContentType("text/html");
      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 public \"-//w3c//dtd html 4.0 " +          "transitional//en\">\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's compile the servlet above and create the following entry .xml the web server 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 http://localhost:8080/SendEmail the URL and the url. This sends an email to a given email ID [email protected] and displays the response shown below:

Send an e-mail message

Successfully sent a message...

If you want to send an e-mail message to more than one recipient, use the following method to specify multiple e-mail IDs:

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

Here's a description of the parameters:

  • type: This will be set to TO, CC, or BCC. H ere, CC stands for CC, BCC stands for BCC. For example Message.RecipientType.TO .
  • Addresss: This is an array of e-mail IDs. When you specify an e-mail ID, you need to use the InternetAddress() method.

Send an HTML e-mail message

The following example sends an HTML-formatted e-mail message from your computer. H ere is assuming that your local host is connected to the Internet and supports sending e-mail. Also ensure that all jar files for the Java Email API package and the JAF package are available in CLASSPATH.

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

With this instance, you can send HTML content of an 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 = "[email protected]";
 
      // 发件人的电子邮件 ID
      String from = "[email protected]";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
      // 设置响应内容类型
      response.setContentType("text/html");
      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 public \"-//w3c//dtd html 4.0 " +          "transitional//en\">\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 servlet above to send HTML messages on a given e-mail ID.

Send attachments in an e-mail message

The following example sends an e-mail message with an attachment from your computer. H ere is assuming that your local host is connected to the Internet and supports sending e-mail. Also ensure that all jar files for the Java Email API package and the JAF package are available in 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 = "[email protected]";
 
      // 发件人的电子邮件 ID
      String from = "[email protected]";
 
      // 假设您是从本地主机发送电子邮件
      String host = "localhost";
 
      // 获取系统的属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象
      Session session = Session.getDefaultInstance(properties);
      
     // 设置响应内容类型
      response.setContentType("text/html");
      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 public \"-//w3c//dtd html 4.0 " +          "transitional//en\">\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 servlet above to send a message with file attachments on a given e-mail ID.

The user authentication section

If you need to provide the e-mail server with a user ID and password for authentication, you can set the following properties:

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

The rest of the e-mail delivery mechanism is consistent with the one explained above.