Servlet 發(fā)送電子郵件

2022-07-23 14:50 更新

Servlet 發(fā)送電子郵件

使用 Servlet 發(fā)送一封電子郵件是很簡(jiǎn)單的,但首先您必須在您的計(jì)算機(jī)上安裝 JavaMail APIJava Activation Framework)JAF)

下載并解壓縮這些文件,在新創(chuàng)建的頂層目錄中,您會(huì)發(fā)現(xiàn)這兩個(gè)應(yīng)用程序的一些 jar 文件。您需要把 mail.jaractivation.jar 文件添加到您的 CLASSPATH 中。

發(fā)送一封簡(jiǎn)單的電子郵件

下面的實(shí)例將從您的計(jì)算機(jī)上發(fā)送一封簡(jiǎn)單的電子郵件。這里假設(shè)您的本地主機(jī)已連接到互聯(lián)網(wǎng),并支持發(fā)送電子郵件。同時(shí)確保 Java Email API 包和 JAF 包的所有的 jar 文件在 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";
 
      // 發(fā)件人的電子郵件 ID
      String from = "web@gmail.com";
 
      // 假設(shè)您是從本地主機(jī)發(fā)送電子郵件
      String host = "localhost";
 
      // 獲取系統(tǒng)的屬性
      Properties properties = System.getProperties();
 
      // 設(shè)置郵件服務(wù)器
      properties.setProperty("mail.smtp.host", host);
 
      // 獲取默認(rèn)的 Session 對(duì)象
      Session session = Session.getDefaultInstance(properties);
      
   // 設(shè)置響應(yīng)內(nèi)容類(lèi)型
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try{
         // 創(chuàng)建一個(gè)默認(rèn)的 MimeMessage 對(duì)象
         MimeMessage message = new MimeMessage(session);
         // 設(shè)置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // 設(shè)置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
         // 設(shè)置 Subject: header field
         message.setSubject("This is the Subject Line!");
         // 現(xiàn)在設(shè)置實(shí)際消息
         message.setText("This is actual message");
         // 發(fā)送消息
         Transport.send(message);
         String title = "發(fā)送電子郵件";
         String res = "成功發(fā)送消息...";
         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();
      }
   }
} 

現(xiàn)在讓我們來(lái)編譯上面的 Servlet,并在 web.xml 文件中創(chuàng)建以下條目:

....
 <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>
....

現(xiàn)在通過(guò)訪(fǎng)問(wèn) URL http://localhost:8080/SendEmail 來(lái)調(diào)用這個(gè) Servlet。這將會(huì)發(fā)送一封電子郵件到給定的電子郵件 ID abcd@gmail.com,并將顯示下面所示的響應(yīng):

發(fā)送電子郵件

成功發(fā)送消息...

如果您想要發(fā)送一封電子郵件給多個(gè)收件人,那么請(qǐng)使用下面的方法來(lái)指定多個(gè)電子郵件 ID:

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

下面是對(duì)參數(shù)的描述:

  • type:這將被設(shè)置為 TO、CC 或 BCC。在這里,CC 代表抄送,BCC 代表密件抄送。例如 Message.RecipientType.TO
  • addresses:這是電子郵件 ID 的數(shù)組。當(dāng)指定電子郵件 ID 時(shí),您需要使用 InternetAddress() 方法。

發(fā)送一封 HTML 電子郵件

下面的實(shí)例將從您的計(jì)算機(jī)上發(fā)送一封 HTML 格式的電子郵件。這里假設(shè)您的本地主機(jī)已連接到互聯(lián)網(wǎng),并支持發(fā)送電子郵件。同時(shí)確保 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。

本實(shí)例與上一個(gè)實(shí)例很類(lèi)似,但是這里我們使用 setContent() 方法來(lái)設(shè)置第二個(gè)參數(shù)為 "text/html" 的內(nèi)容,該參數(shù)用來(lái)指定 HTML 內(nèi)容是包含在消息中的。

使用這個(gè)實(shí)例,您可以發(fā)送內(nèi)容大小不限的 HTML 內(nèi)容。

// 文件名 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";
 
      // 發(fā)件人的電子郵件 ID
      String from = "web@gmail.com";
 
      // 假設(shè)您是從本地主機(jī)發(fā)送電子郵件
      String host = "localhost";
 
      // 獲取系統(tǒng)的屬性
      Properties properties = System.getProperties();
 
      // 設(shè)置郵件服務(wù)器
      properties.setProperty("mail.smtp.host", host);
 
      // 獲取默認(rèn)的 Session 對(duì)象
      Session session = Session.getDefaultInstance(properties);
      
      // 設(shè)置響應(yīng)內(nèi)容類(lèi)型
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try{
         // 創(chuàng)建一個(gè)默認(rèn)的 MimeMessage 對(duì)象
         MimeMessage message = new MimeMessage(session);
         // 設(shè)置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // 設(shè)置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
         // 設(shè)置 Subject: header field
         message.setSubject("This is the Subject Line!");

         // 設(shè)置實(shí)際的 HTML 消息,內(nèi)容大小不限
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
         // 發(fā)送消息
         Transport.send(message);
         String title = "發(fā)送電子郵件";
         String res = "成功發(fā)送消息...";
         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();
      }
   }
} 

編譯并運(yùn)行上面的 Servlet ,在給定的電子郵件 ID 上發(fā)送 HTML 消息。

在電子郵件中發(fā)送附件

下面的實(shí)例將從您的計(jì)算機(jī)上發(fā)送一封帶有附件的電子郵件。這里假設(shè)您的本地主機(jī)已連接到互聯(lián)網(wǎng),并支持發(fā)送電子郵件。同時(shí)確保 Java Email API 包和 JAF 包的所有的 jar 文件在 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";
 
      // 發(fā)件人的電子郵件 ID
      String from = "web@gmail.com";
 
      // 假設(shè)您是從本地主機(jī)發(fā)送電子郵件
      String host = "localhost";
 
      // 獲取系統(tǒng)的屬性
      Properties properties = System.getProperties();
 
      // 設(shè)置郵件服務(wù)器
      properties.setProperty("mail.smtp.host", host);
 
      // 獲取默認(rèn)的 Session 對(duì)象
      Session session = Session.getDefaultInstance(properties);
      
     // 設(shè)置響應(yīng)內(nèi)容類(lèi)型
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

       try{
         // 創(chuàng)建一個(gè)默認(rèn)的 MimeMessage 對(duì)象
         MimeMessage message = new MimeMessage(session);
 
         // 設(shè)置 From: header field of the header.
         message.setFrom(new InternetAddress(from));
 
         // 設(shè)置 To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // 設(shè)置 Subject: header field
         message.setSubject("This is the Subject Line!");
 
         // 創(chuàng)建消息部分 
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 填寫(xiě)消息
         messageBodyPart.setText("This is message body");
         
         // 創(chuàng)建一個(gè)多部分消息
         Multipart multipart = new MimeMultipart();
 
         // 設(shè)置文本消息部分
         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);
 
         // 發(fā)送完整的消息部分
         message.setContent(multipart );
 
         // 發(fā)送消息
         Transport.send(message);
         String title = "發(fā)送電子郵件";
         String res = "成功發(fā)送電子郵件...";
         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();
      }
   }
} 

編譯并運(yùn)行上面的 Servlet ,在給定的電子郵件 ID 上發(fā)送帶有文件附件的消息。

用戶(hù)身份認(rèn)證部分

如果需要向電子郵件服務(wù)器提供用戶(hù) ID 和密碼進(jìn)行身份認(rèn)證,那么您可以設(shè)置如下屬性:

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

電子郵件發(fā)送機(jī)制的其余部分與上面講解的保持一致。

以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)