當前位置:首頁 » Servlets » Servlet發送Email

Servlet發送Email

Servlets發送Email實例代碼教學 - 要發送一封電子郵件,使用Servlet是很簡單的,但首先你的機器上已經安裝了JavaMail API和Java激活框架(JAF)。

要發送一封電子郵件,使用Servlet是很簡單的,但首先,你的機器上已經安裝了JavaMail API和Java激活框架(JAF)。

下載並解壓縮這些文件,在新創建的頂層目錄,你會發現兩個應用程序的jar文件。需要在CLASSPATH添加了mail.jar 和activation.jar文件。

發送一個簡單的電子郵件:

下麵是一個例子,從您的計算機發送一個簡單的電子郵件。這裡假設您的本地主機連接到互聯網,並有足夠的能力來發送電子郵件。同時確保所有的jar文件從Java電子郵件API包和JAF包ARA在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 - by www.gitbook.net
      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();
      }
   }
} 

現在讓我們來編譯上麵的servlet在web.xml文件中創建以下條目

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

現在調用這個servlet,使用URL http://localhost:8080/SendEmail,會發送郵件到電子郵件ID為abcd@gmail.com將顯示以下回應:

Send Email

Sent message successfully....

如果你想發送電子郵件給多個收件人,然後下麵的方法將被用來指定多個電子郵件ID:

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

下麵的參數說明:

  • type: 這將被設定為TO,CC或BCC。在這裡,CC代表抄送BCC的Black Carbon複製。例如Message.RecipientType.

  • addresses: 這是數組的電子郵件ID。您將需要使用InternetAddress()方法,同時指定電子郵件ID

發送HTML電子郵件:

下麵是一個例子,從您的計算機發送HTML格式的電子郵件。這裡假設您的本地主機連接到互聯網,並有足夠的能力來發送電子郵件。同時確保所有的jar文件從Java電子郵件API包和JAF包ARA在CLASSPATH。

這個例子是前一個非常相似的,但在這裡我們使用的是setContent()方法來設置內容的第二個參數是“text/html的”指定HTML內容包含在消息中。

使用這個例子中,你可以發送喜歡的HTML內容,內容的大小一般不受限製。

// 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 - by www.gitbook.net
      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發送HTML郵件在一個給定的電子郵件ID。

在電子郵件發送附件:

下麵是一個例子,從您的計算機發送帶有附件的電子郵件。這裡假設您的本地主機連接到互聯網,並有足夠的能力來發送電子郵件。

// 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 - by www.gitbook.net
      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消息。

用戶身份驗證部分:

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

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

如上麵所解釋的電子郵件發送機製,其餘部分將保持。