使用 Servlet 发送一封电子邮件是很简单的,但首先您必须在您的计算机上安装 JavaMail APIJava Activation Framework)JAF)

下载并解压缩这些文件,在新创建的顶层目录中,您会发现这两个应用程序的一些 jar 文件。您需要把 mail.jaractivation.jar 文件添加到您的 CLASSPATH 中。

发送一封简单的电子邮件

下面的实例将从您的计算机上发送一封简单的电子邮件。这里假设您的本地主机已连接到互联网,并支持发送电子邮件。同时确保 Java Email API 包和 JAF 包的所有的 jar 文件在 CLASSPATH 中都是可用的。

 1 // 文件名 SendEmail.java
 2 import java.io.*;
 3 import java.util.*;
 4 import javax.servlet.*;
 5 import javax.servlet.http.*;
 6 import javax.mail.*;
 7 import javax.mail.internet.*;
 8 import javax.activation.*;
 9  
10 public class SendEmail extends HttpServlet{
11     
12   public void doGet(HttpServletRequest request,
13                     HttpServletResponse response)
14             throws ServletException, IOException
15   {
16       // 收件人的电子邮件 ID
17       String to = "abcd@gmail.com";
18  
19       // 发件人的电子邮件 ID
20       String from = "web@gmail.com";
21  
22       // 假设您是从本地主机发送电子邮件
23       String host = "localhost";
24  
25       // 获取系统的属性
26       Properties properties = System.getProperties();
27  
28       // 设置邮件服务器
29       properties.setProperty("mail.smtp.host", host);
30  
31       // 获取默认的 Session 对象
32       Session session = Session.getDefaultInstance(properties);
33       
34       // 设置响应内容类型
35       response.setContentType("text/html");
36       PrintWriter out = response.getWriter();
37 
38       try{
39          // 创建一个默认的 MimeMessage 对象
40          MimeMessage message = new MimeMessage(session);
41          // 设置 From: header field of the header.
42          message.setFrom(new InternetAddress(from));
43          // 设置 To: header field of the header.
44          message.addRecipient(Message.RecipientType.TO,
45                                   new InternetAddress(to));
46          // 设置 Subject: header field
47          message.setSubject("This is the Subject Line!");
48          // 现在设置实际消息
49          message.setText("This is actual message");
50          // 发送消息
51          Transport.send(message);
52          String title = "发送电子邮件";
53          String res = "成功发送消息...";
54          String docType =
55          "<!doctype html public \"-//w3c//dtd html 4.0 " +
56          "transitional//en\">\n";
57          out.println(docType +
58          "<html>\n" +
59          "<head><title>" + title + "</title></head>\n" +
60          "<body bgcolor=\"#f0f0f0\">\n" +
61          "<h1 align=\"center\">" + title + "</h1>\n" +
62          "<p align=\"center\">" + res + "</p>\n" +
63          "</body></html>");
64       }catch (MessagingException mex) {
65          mex.printStackTrace();
66       }
67    }
68 } 
View Code

相关文章:

  • 2021-07-08
  • 2022-02-18
  • 2021-08-08
  • 2021-09-11
  • 2022-02-19
  • 2021-07-25
  • 2022-12-23
  • 2021-08-04
猜你喜欢
  • 2022-12-23
  • 2021-12-01
  • 2021-09-10
  • 2021-10-28
  • 2021-08-04
  • 2021-09-12
相关资源
相似解决方案