Servlet如何发送电子邮件呢?
下文讲述Servlet发送电子邮件的方法分享,如下所示:
实现思路: Java发送邮件,通常笔者建议使用 JavaMail mail.jar 1.4.5 JAF(版本1.1.1)activation.jar 然后借助相应的API,进行电子邮件发送例:
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; @Servlet("/sendMail") public class SendEmail extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //收件人电子邮件ID String to = "admin@java265.com"; //发件人电子邮件ID String from = "admin@java265.com"; //假设您是从本地主机发送电子邮件 String host = "localhost"; //获取系统属性 Properties properties = System.getProperties(); //设置邮件服务器 properties.setProperty("mail.smtp.host", host); //获取默认Session对象 Session session = Session.getDefaultInstance(properties); //设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try{ // 创建一个默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // 设置 From: header field of the header. message.setFrom(new InternetAddress(from)); // 设置 To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置 Subject: header field message.setSubject("This is the Subject Line!"); // 现在设置实际消息 message.setText("This is actual message"); // 发送消息 Transport.send(message); String title = "发送电子邮件"; String res = "成功发送消息..."; String docType = "<!DOCTYPE html> \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(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。