Springboot系列之Springboot的邮件服务

前言

Springboot集常用的功能于一体,当然邮件功能作为最常见的功能,自然不能缺席Springboot的大家庭,spring-boot-starter-mail这个jar里面封装了SpringBoot的邮件功能。下面来看一下常见的邮件用途

预备知识:
Springboot 2.1.1
Maven 3.5.3
Lomlok 1.16.18(可以参考:lombok 简化 Java 代码)
thymeleaf:3.0.11
junit 4.12

代码地址:
博文只是列举核心操作步骤,需要自己实际操作。
https://github.com/Tojian/spring-treasure-box/tree/master/tao-springboot-mail

一、pom文件添加mail相关依赖

邮件功能主要用到这个spring-boot-starter-mail这个starter,这个Starter里面集成了很多java的mail和spring框架里面的一些mail操作,比如核心的JavaMailSender类就是在Spring-context里面封装的。

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

二、在application.properties中添加邮箱配置

# 邮箱服务器名字
spring.mail.host=smtp.163.com
# 发送方邮箱地址
spring.mail.username=tj_since@163.com
# 授权码
spring.mail.password=XXX
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

# 收件邮箱地址
mail.sender.to=1099593012@qq.com

说明一下spring.mail.password 这个并不是你的邮箱密码,而是你的邮箱的授权码,下面以163邮箱截图说明



三.简单邮件实现

1.代码实现

@Autowired
    private TemplateEngine templateEngine;

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

    @Value("${mail.sender.to}")
    private String to;

    @Override
    public void sendTxtMail(String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            log.info("send simple mail done");
        } catch (Exception e) {
            log.error("send simple mail happen exception", e);
        }

    }

2.代码测试

@Test
    public void testSimpleMail() throws Exception {
        mailSend.sendTxtMail("test simple mail", " hello this is text mail");
    }

四.发送Html格式

1.代码实现

 @Override
    public void sendHtmlMail(String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // 设置为true
            helper.setText(content, true);
            mailSender.send(message);
            log.info("send html mail done");
        } catch (MessagingException e) {
            log.error("send html mail happen exception", e);
        }
    }

2.代码测试

    @Test
    public void testHtmlMail() throws Exception {
        String content = "<html>\n" +
                "<body>\n" +
                "    <h3>hello world ! 这是一封Html邮件!</h3>\n" +
                "</body>\n" +
                "</html>";
        mailSend.sendHtmlMail("test simple mail", content);
    }

五.发送附件

1.代码实现


    @Override
    public void sendAttachmentsMail(String subject, String content,String path) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();

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

            FileSystemResource file = new FileSystemResource(new File(path));
            helper.addAttachment("附件-1.jpg", file);
            helper.addAttachment("附件-2.jpg", file);
            mailSender.send(mimeMessage);
            log.info("send AttachmentsMail done ");
        } catch (Exception e) {
            log.error("send AttachmentsMail happen exception");
        }
    }

2.代码测试

  @Test
    public void testsendAttachmentsMail() {
        String path = "/Users/taojian/Files/projectSofeware/github/spring-treasure-box/tao-springboot-mail/src/test/java/com/taojian/mail/tao.jpg";
        mailSend.sendAttachmentsMail("附件发送", "有附件", path);
    }

六.发送静态资源内嵌

1.代码实现

   @Override
    public void sendInlineMail(String subject, String content,String path) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(path));
            helper.addInline("tao", file);
            mailSender.send(mimeMessage);
            log.info("send InlineMail done ");
        } catch (Exception e) {
            log.error("send InlineMail happen exception");
        }

    }

2.代码测试

 @Test
    public void testsendInlineMail() {
        String content = "<html><body><img src=\"cid:tao\" ></body></html>";
        String path = "/Users/taojian/Files/projectSofeware/github/spring-treasure-box/tao-springboot-mail/src/test/java/com/taojian/mail/tao.jpg";
        mailSend.sendInlineMail("sendInlineMail", content, path);
    }

七.发送邮件模版

1.代码实现

1.创建邮件模版email.html

这里采用了org.springframework.boot:spring-boot-starter-thymeleaf:2.1.1.RELEASE,thymeleaf和springboot有很好的集成,官方也推荐这种方式

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
您好     <td th:text="${username}"></td>,这是验证邮件,请点击下面的链接完成验证,<br/>
<a href="#" th:href="@{ http://www.taobigbig.com/ }">激活账号</a>
</body>
</html>

2.java代码


    @Override
    public void sendTemplateMail(String title, String content) {
        try {
            //创建邮件正文
            Context context = new Context();
            context.setVariable("username", "taojian");
            // email是邮件模版
            String emailContent = templateEngine.process("email", context);
            MimeMessage mimeMessage = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(emailContent,true);

            mailSender.send(mimeMessage);
            log.info("send TemplateMail done ");
        } catch (Exception e) {
            log.error("send TemplateMail happen exception");
        }
    }

2.代码测试

  @Test
    public void testsendTemplateMail() {

        mailSend.sendTemplateMail("send mail template", "send mail template test");
    }

五、参考文献

http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html
http://tengj.top/categories/Spring-Boot%E5%B9%B2%E8%B4%A7%E7%B3%BB%E5%88%97/
https://blog.csdn.net/clementad/article/details/51833416
https://github.com/pkhanal/spring-boot-starter-mail-sample
http://repo.spring.io/release/org/springframework/boot/spring-boot-starter-mail/


欢迎关注技术公众号:Coder辰砂(太难听的,有谁能帮我想个普通技术相关的公众号,想不到,暂时用这个吧)
公众号主要整理自己的一些技术方向的,计算机基础课程,java框架,分布式等。

posted @ 2019-01-04 19:32  辰砂tj  阅读(...)  评论(... 编辑 收藏