JavaWeb 发送邮件

我们可以使用第三方的邮箱服务器来发送邮件。

常用的邮件传输协议有2种:POP3/SMTP、IMAP/SMTP

POP和IMAP的区别:在邮箱客户端的操作,比如移动邮件、标记已读,如果使用POP,是不会同步到邮箱服务器上的;如果使用IMAP,这些操作会同步到邮箱服务器上。

需要2个jar包

  • javax.mail.jar
  • activation.jar

示例   使用QQ邮箱服务器发送邮件

此处使用IMAP。可在 设置->账户 -> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 中配置。

@WebServlet("/sendMailServlet")
public class SendMailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 邮箱服务器主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");//是否使用ssl安全连接
        properties.put("mail.debug", "true");//是否在控制台显示相关信息

        //获取会话对象
        Session session = Session.getInstance(properties);
        //获取邮件对象
        Message message = new MimeMessage(session);

        try {
            // 设置发件人邮箱地址
            message.setFrom(new InternetAddress("[email protected]"));
            // 设置收件人邮箱地址
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

            //有多个收件人时,写成数组形式
            //InternetAddress[] receiverArr={new InternetAddress("[email protected]"),new InternetAddress("[email protected]"),new InternetAddress("[email protected]")};
            //message.setRecipients(Message.RecipientType.TO, receiverArr);

            // 设置邮件标题
            message.setSubject("邮件标题");
            // 设置邮件内容
            message.setText("邮件内容");

            //获取邮差对象
            Transport transport = session.getTransport();
            //连接自己的邮箱账户,第二个参数是授权码
            transport.connect("[email protected]", "xxxxxxxxxxx");
            //发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

使用时修改红字部分即可。

猜你喜欢

转载自www.cnblogs.com/chy18883701161/p/11448310.html
今日推荐