Spring Boot-实现邮件发送

相信使用过Spring的众多开发者都知道Spring提供了很是好用的JavaMailSender接口实现邮件发送,在Spring Boot的Starter模块中也为此提供了自动化配置,下面经过实例看看如何在Spring Boot中使用JavaMailSender发送邮件,本文以@163.com邮箱为例阐述。html


What-什么是邮件服务

邮件服务在互联网早期就已经出现,现在已成为人们互联网生活中必不可少的一项服务。那么邮件服务是怎么工做的呢?以下给出邮件发送与接收的典型过程:
一、发件人使用SMTP协议传输邮件到邮件服务器A;
二、邮件服务器A根据邮件中指定的接收者,投送邮件至相应的邮件服务器B;
三、收件人使用POP3协议从邮件服务器B接收邮件。
SMTP(Simple Mail Transfer Protocol)是电子邮件(email)传输的互联网标准,定义在RFC5321,默认使用端口25;
POP3(Post Office Protocol - Version 3)主要用于支持使用客户端远程管理在服务器上的电子邮件。定义在RFC 1939,为POP协议的第三版(最新版)。
这两个协议均属于TCP/IP协议族的应用层协议,运行在TCP层之上。
咱们平常收发邮件使用的客户端、Web Mail的背后都在运行着这两个协议,完成收发邮件的过程。而如今咱们须要使用SMTP协议来把发送给用户的邮件传输到邮件服务器。
从客户端传输邮件到服务器须要双方的配合,而规则就定义在SMTP协议中。咱们如今须要作的是找一个SMTP服务器,再实现一个SMTP客户端,而后让客户端发送邮件到服务器。java


Why-为何系统要创建邮件服务

电子邮件具备全世界通用的协议。因此你可使用任何一种邮件的客户端,以任何一种方式去查看你的邮件。这个世界上的电子邮件客户端不下千种,他们都以不一样的方式去知足了不一样需求的人群,邮件有如下特色:
① 企业内部的沟通,邮件服务仍是被认为“正式”的,比即时通讯“可靠”。
② 支持转发/抄送,公开的,统一的通讯协议,可以存档。spring


Why-如何实现邮件服务

  • 配置邮件服务器

开启SMTP服务器,设置受权码,后续编写代码须要改受权码,编码中的密码非邮箱登陆密码而是受权码,如:设置受权码为:123456。
图片描述json


  • 实现邮件客户端

① Gradle添加Spring Mail依赖服务器

compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'

② 修改application.properties,添加邮箱配置app

##################################---Spring Mail发送邮件---##############################################
# JavaMailSender 邮件发送的配置
spring.mail.default-encoding=UTF-8 
spring.mail.host=smtp.163.com
spring.mail.port=465
spring.mail.username=javalsj@163.com
# 邮箱开启的受权码
spring.mail.password=123456
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true

  • 编写发送邮件工具JavaMailUtil代码,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
package com.javalsj.blog.mail;

import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.javalsj.blog.common.FileUtil;

/**
 * @description 发送邮件工具,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
 * @author WANGJIHONG
 * @date 2018年3月14日 下午10:17:40
 * @Copyright 版权全部 (c) www.javalsj.com
 * @memo 无备注说明
 */
@Component
public class JavaMailUtil {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Java邮件发送器
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * thymeleaf模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送不含附件,且不含嵌入html静态资源页面的纯文本简单邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receiver
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopy
     *            抄送人,可多个抄送人 如:33333@sohu.com
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     */
    public void sendSimpleEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, null);
    }

    /**
     * 发送含嵌入html静态资源页面, 但不含附件的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receivers
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:3333@sohu.com
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如: <html><body>
     *            <h1>213123</h1></body></html>
     */
    public void sendHtmlEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
            throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送含附件,但不含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receivers
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:3333@sohu.com.cn
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     */
    public void sendAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, attachmentFilePaths);
    }

    /**
     * 发送含附件,且含嵌入html静态资源页面的邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receivers
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:33333@jiuqi.com.cn
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            <html><body><img src=\"cid:test\"><img
     *            src=\"cid:test2\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
     *            http://www.javalsj.com/resource/test2.jpg
     *            须要注意的是addInline函数中资源名称attchmentFileName须要与正文中cid:attchmentFileName对应起来
     */
    public void sendHtmlAndAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
            String text, String[] attachmentFilePaths) throws Exception {
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, attachmentFilePaths);
    }

    /**
     * 发送thymeleaf模板邮件
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receivers
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:33333@sohu.com
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param thymeleafTemplatePath
     *            邮件模板 如:mail\mailTemplate.html。
     * @param thymeleafTemplateVariable
     *            邮件模板变量集 
     */
    public void sendTemplateEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String thymeleafTemplatePath,
            Map<String, Object> thymeleafTemplateVariable) throws Exception {
        String text = null;
        if (thymeleafTemplateVariable != null && thymeleafTemplateVariable.size() > 0) {
            Context context = new Context();
            thymeleafTemplateVariable.forEach((key, value)->context.setVariable(key, value));
            text = templateEngine.process(thymeleafTemplatePath, context);
        }
        sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
    }

    /**
     * 发送的邮件(支持带附件/html类型的邮件)
     * 
     * @param deliver
     *            发送人邮箱名 如: javalsj@163.com
     * @param receivers
     *            收件人,可多个收件人 如:11111@qq.com,2222@163.com
     * @param carbonCopys
     *            抄送人,可多个抄送人 如:3333@sohu.com
     * @param subject
     *            邮件主题 如:您收到一封高大上的邮件,请查收。
     * @param text
     *            邮件内容 如:测试邮件逗你玩的。 <html><body><img
     *            src=\"cid:attchmentFileName\"></body></html>
     * @param attachmentFilePaths
     *            附件文件路径 如:
     *            须要注意的是addInline函数中资源名称attchmentFileName须要与正文中cid:attchmentFileName对应起来
     * @throws Exception
     *             邮件发送过程当中的异常信息
     */
    private void sendMimeMail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text,
            boolean isHtml, String[] attachmentFilePaths) throws Exception {
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(deliver);
            helper.setTo(receivers);
            helper.setCc(carbonCopys);
            helper.setSubject(subject);
            helper.setText(text, isHtml);
            // 添加邮件附件
            if (attachmentFilePaths != null && attachmentFilePaths.length > 0) {
                for (String attachmentFilePath : attachmentFilePaths) {
                    File file = new File(attachmentFilePath);
                    if (file.exists()) {
                        String attachmentFile = attachmentFilePath
                                .substring(attachmentFilePath.lastIndexOf(File.separator));
                        long size = FileUtil.getDirSize(file);
                        if (size > 1024 * 1024) {
                            String msg = String.format("邮件单个附件大小不容许超过1MB,[%s]文件大小[%s]。", attachmentFilePath,
                                    FileUtil.formatSize(size));
                            throw new RuntimeException(msg);
                        } else {
                            FileSystemResource fileSystemResource = new FileSystemResource(file);
                            helper.addInline(attachmentFile, fileSystemResource);
                        }
                    }
                }
            }
            mailSender.send(mimeMessage);
            stopWatch.stop();
            logger.info("邮件发送成功, 花费时间{}秒", stopWatch.getTotalTimeSeconds());
        } catch (Exception e) {
            logger.error("邮件发送失败, 失败缘由 :{} 。", e.getMessage(), e);
            throw e;
        }
    }

}

  • 编写简单文本邮件发送控制器
@RequestMapping(value = "/sendSimpleEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendSimpleEmail() {
        Result result;
        try {
            javaMailUtil.sendSimpleEmail("javalsj@163.com", new String[] { "1111@qq.com", "2222@qq.com" },
                    new String[] { "33333@sohu.com" }, "您收到一封高大上的邮件,请查收。", "测试邮件逗你玩的。");
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

效果以下:
图片描述函数


  • 编写模板引擎页面邮件发送

图片描述

mailTemplate.html页面代码:spring-boot

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
    <div>
        用户名:<input th:text="${username}"/> <br /> 
        密码: <input th:text="${password}"/>
    </div>
</body>
</html>

控制器测试代码:工具

@RequestMapping(value = "/sendTemplateEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result sendTemplateEmail() {
        Result result = null;
        try {
            String thymeleafTemplatePath = "mail/mailTemplate";
            Map<String, Object> thymeleafTemplateVariable = new HashMap<String, Object>();
            thymeleafTemplateVariable.put("username", "javalsj");
            thymeleafTemplateVariable.put("password", "123456");
            javaMailUtil.sendTemplateEmail("javalsj@163.com", 
                    new String[] { "11111@qq.com", "22222@qq.com" },
                    new String[] { "3333@sohu.com" }, 
                    "您收到一封高大上的邮件,请查收。",
                    thymeleafTemplatePath,
                    thymeleafTemplateVariable);
            result = ResultFactory.buildSuccessResult(null);
        } catch (Exception e) {
            result = ResultFactory.buildFailResult(e.getMessage());
        }
        return result;
    }

效果以下:
图片描述测试


总结

本文使用Spring Boot + JavaMailSender + Thymeleaf实现了服务端发送纯文本邮件、html邮件、附件邮件以及Thymeleaf模板邮件功能,因为Spring Boot默认模板引擎为Thymeleaf,因此使用默认的Thymeleaf自动配置便可,本文未作Thymeleaf的单独配置。

相关文章
相关标签/搜索