Servlet发送邮件

以下内容引用自http://wiki.jikexueyuan.com/project/servlet/sending-email.html

使用Servlet发送一封电子邮件是非常简单的,但是开始之前必须在计算机上安装JavaMail API和Java Activation Framework(JAF)。

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

POM项目添加如下依赖:

        <!-- JavaMail Library -->
        <!-- http://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.6</version>
        </dependency>

一、发送一封简单的电子邮件

//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";// This is SMTP Server,Ex:smtp.163.com
        // set email username
        String user = "user";
        // set email password
        String password = "password";
        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.user", user);
        properties.setProperty("mail.password", password);
        // 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>
....

 

如果想把一封电子邮件发送给多个收件人,那么使用下面的方法来指定多个电子邮件ID:

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

这里是对参数的描述:

  • type:这将被设置为TO、CC或BCC。这里CC代表抄送且BCC代表密件抄送。例如Message.RecipientType.TO。

  • addresses:这是电子邮件ID的数组。当指定电子邮件ID时,需要使用InternetAddress()方法。

二、发送一封HTML电子邮件

这个例子与上一个例子非常相似,除了在这里使用的是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 SendEmail1 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";//This is SMTP Server,Ex:smtp.163.com
        // set email username
        String user = "user";
        // set email password
        String password = "password";
        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.user", user);
        properties.setProperty("mail.password", password);
        // 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并在web.xml文件中创建以下条目:

    <servlet>
        <servlet-name>SendEmail</servlet-name>
        <servlet-class>com.jsoft.testservletbasics.SendEmail1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SendEmail</servlet-name>
        <url-pattern>/SendEmail</url-pattern>
    </servlet-mapping>

三、在电子邮件中发送附件

//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 SendFile 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";// This is SMTP Server,Ex:smtp.163.com
        // set email username
        String user = "user";
        // set email password
        String password = "password";
        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.user", user);
        properties.setProperty("mail.password", password);
        // 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并在web.xml文件中创建以下条目:

    <servlet>
        <servlet-name>SendEmail</servlet-name>
        <servlet-class>com.jsoft.testservletbasics.SendFile</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SendEmail</servlet-name>
        <url-pattern>/SendEmail</url-pattern>
    </servlet-mapping>

四、用户身份认证部分

如果需要向电子邮件服务器提供用户ID和密码来进行身份认证,那么可以设置如下所示的属性:

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

 

电子邮件发送机制的其余部分与上面解释的一致。

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/servletbasics/test16

posted @ 2017-06-11 18:28  EasonJim  阅读(553)  评论(0编辑  收藏  举报