Spring Boot 技术探索

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

34、Spring Boot之Email的收发

平台环境:

名称

版本号

Mac OS X

10.15.2

JDK

1.8.0_201

Apache Maven

3.6.0

IntelliJ IDEA

2019.3 (Ultimate Edition)

Spring Boot

2.2.2.RELEASE

 

  回顾,Email的收发过程?

  第一步、发件人使用使用本机客户端或浏览器通过Email地址、密码登录邮件服务器,并补充完整要发送邮件的收件人地址、标题、内容等信息—>通过SMTP协议等一系列互联网协议—>把邮件内容送达到收件人SMTP服务器并存入存储设备。

  第二步,收件人使用本机客户端或浏览器通过Email地址、密码登录邮件服务器—>通过POP3等一系列互联网协议把邮件接收到本机—>就可以查看邮件了。

 

DEMO

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

 

application.properties

spring.mail.host=smtp.exmail.qq.com
spring.mail.username=admin@codelabx.com
spring.mail.password=XXXXXX
spring.mail.default-encoding=UTF-8

 

MailService

package com.example.demo.service;


public interface MailService
{
    void sendSimpleMail(String to, String subject, String content);


    void sendHtmlMail(String to, String subject, String content);


    void sendAttachmentsMail(String to, String subject, String content, String filePath);


    void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
}

 

MailServiceImpl

package com.example.demo.service.impl;


import com.example.demo.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;


@Component
public class MailServiceImpl implements MailService
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private JavaMailSender mailSender;

    @Autowired
    public void setMailSender(JavaMailSender mailSender)
    {
        this.mailSender = mailSender;
    }

    @Value("${spring.mail.username}")
    private String from;

    // 发送文本邮件
    @Override
    public void sendSimpleMail(String to, String subject, String content)
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try
        {
            mailSender.send(message);
            logger.info("SimpleMail已发送");
        } catch (Exception e)
        {
            logger.error("SimpleMail发送异常!", e);
            throw e;
        }
    }


    // 发送html邮件
    @Override
    public void sendHtmlMail(String to, String subject, String content)
    {
        MimeMessage message = mailSender.createMimeMessage();

        try
        {
            // 通过MimeMessageHelper来为MimeMessage设置各项属性
            MimeMessageHelper helper = new MimeMessageHelper(message, true); // true表示需要创建一个multipart message
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);  // true表示接收content type "text/html"类型,默认content type ("text/plain")


            mailSender.send(message);
            logger.info("HtmlMail已发送");
        } catch (MessagingException e)
        {
            logger.error("HtmlMail发送异常!", e);
        }
    }


    // 发送带附件的邮件
    public void sendAttachmentsMail(String to, String subject, String content, String filePath)
    {
        MimeMessage message = mailSender.createMimeMessage();

        try
        {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            logger.info("AttachmentsMail已发送");
        } catch (MessagingException e)
        {
            logger.error("AttachmentsMail发送异常!", e);
        }
    }


    // 发送正文中有静态资源(图片)的邮件
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId)
    {
        MimeMessage message = mailSender.createMimeMessage();

        try
        {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            logger.info("InlineResourceMail已发送");
        } catch (MessagingException e)
        {
            logger.error("InlineResourceMail发送异常!", e);
        }
    }
}

 

接下来就可以开始测试了。

MailServiceTest

package com.example.demo;


import com.example.demo.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
public class MailServiceTest
{
    @Autowired
    private MailService mailService;


    @Test
    public void testSimpleMail()
    {
        mailService.sendSimpleMail("123456@qq.com", "This is simple mail", " Hello, This is simple mail.");
    }


    @Test
    public void testHtmlMail()
    {
        String content = "<html><body><h1>Hello,这是一封html邮件!</h1><h3>这行字体应该比上一行要小。</h3></body></html>";
        mailService.sendHtmlMail("123456@qq.com", "This is HTML mail", content);
    }


    @Test
    public void sendAttachmentsMail()
    {
        String filePath = "/Users/wang/Downloads/notice.zip";
        mailService.sendAttachmentsMail("123456@qq.com", "This is Attachments mail", "Hello, This is Attachments mail.", filePath);
    }


    @Test
    public void sendInlineResourceMail()
    {
        String rscId = "IMG_20191007_155634_1";
        String content = "<html><body>hi~,分享我的新摄影作品:<br /><img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "/Users/wang/Downloads/IMG_20191007_155634_1.jpg";


        mailService.sendInlineResourceMail("123456@qq.com", "This is Inline Resource mail", content, imgPath, rscId);
    }
}

 

可以看出,邮件中存在普通的文本内容还容易阅读,但是在使用HTML标签的情况下随着标签数量的增多和复杂度的提高,代码阅读越来越困难。

这种情况就需要引入Thymeleaf模板来解决。

 

pom.xml引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

路径src/main/resources/templates/emailTemplate.html

新建模板文件emailTemplate.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    您好,欢迎来到CodelabX,请点击下面的链接完成邮箱验证。<br/>
    <a href="#" th:href="@{ http://www.codelabx.com/register/mailCheck/{checkCode}(checkCode=${checkCode}) }">激活账号</a>
</body>
</html>

 

测试类增加测试方法sendTemplateMail

package com.example.demo;


import com.example.demo.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


@SpringBootTest
public class MailServiceTest
{
    @Autowired
    private MailService mailService;


    @Autowired
    private TemplateEngine templateEngine;


    @Test
    public void sendTemplateMail()
    {
        Context context = new Context();
        context.setVariable("checkCode", "45CB0D8F_09100037_7D1056EB_A1DDC1A2");
        String emailContent = templateEngine.process("emailTemplate", context);


        mailService.sendHtmlMail("123456@qq.com", "This is Template mail", emailContent);
    }
}

 

 

Bootstrap Thumbnail Second
MySQL

MySQL is the world's most popular open source database.

GO

Bootstrap Thumbnail Third
算法基础

本书介绍了什么是计算机算法,如何描述它们,以及如何来评估它们。

GO