發(fā)送電子郵件

2018-08-12 21:20 更新

發(fā)送電子郵件

使用 Servlet 發(fā)送一封電子郵件是非常簡單的,但是開始之前你必須在你的計算機上安裝 JavaMail APIJava Activation Framework(JAF)。

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

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

這是從你的計算機上發(fā)送一封簡單的電子郵件的實例。這里假設你的本地主機已連接到互聯(lián)網(wǎng)并可以發(fā)送電子郵件。同時確保來自 Java Email API 包和 JAF 包的所有的 jar 文件在 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 needs to be mentioned.
      String to = "abcd@gmail.com"; 
      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";
      // 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");
      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 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" +
         "<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)在讓我們來編譯上述 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)在使用 URL http://localhost:8080/SendEmail 來調(diào)用這個 servlet。這將會給給定的電子郵件 ID abcd@gmail.com 發(fā)送一封電子郵件并將顯示如下所示的響應:

Send Email

Sent message successfully....

如果你想把一封電子郵件發(fā)送給多個收件人,那么使用下面的方法來指定多個電子郵件 ID:

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

這里是對參數(shù)的描述:

  • type:這將被設置為 TO、CC 或 BCC。這里 CC 代表抄送且 BCC 代表密件抄送。例如 Message.RecipientType.TO。

  • addresses:這是電子郵件 ID 的數(shù)組。當指定電子郵件 ID 時,你需要使用 InternetAddress() 方法。

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

這個例子將從你的計算機上發(fā)送一封 HTML 電子郵件。這里假設你的本地主機已連接到互聯(lián)網(wǎng)且可以發(fā)送電子郵件。同時確保來自 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。

這個例子與上一個例子非常相似,除了在這里我們使用的是 setContent() 方法來設置內(nèi)容,它的第二個參數(shù)為 “text/html” 用來指定 HTML 內(nèi)容是包含在消息中的。

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

// 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 needs to be mentioned.
      String to = "abcd@gmail.com";
      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com"; 
      // 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");
      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!");
         // Send the actual HTML message, as big as you like
         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 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();
      }
   }
} 

編譯并運行上述 servlet 來在給定的電子郵件 ID 上發(fā)送 HTML 消息。

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

這里的例子將從你的計算機上發(fā)送一封帶有附件的電子郵件。這里假設你的本地主機已連接到互聯(lián)網(wǎng)并能夠發(fā)送電子郵件。同時確保來自 Java Email API 包和 JAF 包的所有的 jar 文件在 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 needs to be mentioned.
      String to = "abcd@gmail.com"; 
      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";
      // 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");
      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" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
} 

編譯并運行上面的 servlet 來在給定的電子郵件 ID 上發(fā)送附件文件和消息。

用戶身份認證部分

如果需要向電子郵件服務器提供用戶 ID 和密碼來進行身份認證,那么你可以設置如下所示的屬性:

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

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

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號