Servlet-发送电子邮件

①Servlet发送电子邮件

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

  • 您可以从 Java 网站下载最新版本的 JavaMail mail.jar 1.4.5
  • 您可以从 Java 网站下载最新版本的 JAF(版本 1.1.1) activation.jar

②文件目录

   --mailSendSucc.jsp

   --SendMail.java

@WebServlet("/sendMail")
public class SendMail extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Properties props = new Properties();

            // 开启debug调试
            props.setProperty("mail.debug", "true");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "smtp.163.com");
            // props.setProperty("mail.port", "465");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            Session session = Session.getInstance(props);

            Message msg = new MimeMessage(session);
            msg.setSubject("邮件服务");
            StringBuilder builder = new StringBuilder();
            //            builder.append("url = " + "http://blog.csdn.net/never_cxb/article/details/50524571");
            builder.append("\nhello qxl from ryan");
            builder.append("\n时间 " + new Date());
            msg.setText(builder.toString());
            msg.setFrom(new InternetAddress("[email protected]"));

            Transport transport = session.getTransport();
            transport.connect("smtp.163.com", "[email protected]", "520025zyqq");

            transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });

            transport.close();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        request.setAttribute("message", "邮件上传成功");
        request.getServletContext().getRequestDispatcher("/mailSendSucc.jsp").forward(request, response);

    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>



    
    邮件上传结果


${message}

 

你可能感兴趣的:(Servlet)