Fork me on GitHub

SpringBoot系列之发送邮件极速入门与实践

一、Email前言介绍

邮件发送业务,是很多公司都有的,本博客介绍一下基于SpringBoot的邮件发送功能,邮箱服务基于腾讯QQ邮箱

SpringBoot的肯定有很多场景启动器starter,SpringBoot官方提供了spring-boot-starter-mail作为邮件服务的场景启动器

二、Email例子实践

2.1 开发实验环境准备

  • JDK 1.8
  • SpringBoot2.2.1
  • Maven 3.2+
  • 开发工具
    • IntelliJ IDEA
    • smartGit

创建一个SpringBoot Initialize项目,详情可以参考我之前博客:SpringBoot系列之快速创建项目教程

2.2 Meavn配置文件

配置spring-boot-starter-mail:

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

配置Thymeleaf模板引擎

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

lombok,非必须,只是不想写bean类的set,get

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.3 application配置

新建application.yml,注意password在QQ邮箱里不是邮箱密码,需要去申请SMTP服务给的secret

spring:
  mail:
    host: smtp.qq.com
    username: your_emial@qq.com
    password: cmlebzqdtvejdibe
    default-encoding: utf-8

向腾讯申请secret:
在这里插入图片描述
网易163邮箱的配置:

spring: 
    mail:
        host: smtp.163.com
        username: your163account@163.com
        password: your163password
        default-encoding: utf-8

2.4 发送文本格式邮件

Email DTO类:

package com.example.springboot.email.bean;

import lombok.Data;

/**
 * <pre>
 *      EmailDto
 * </pre>
 *
 * <pre>
 * @author mazq
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/22 16:26  修改内容:
 * </pre>
 */
@Data
public class EmailDto {

    /**
     * 发送对象
     */
    private String sendTo;
    /**
     * 发送主题
     */
    private String subject;
    /**
     * 邮件内容
     */
    private String content;
    /**
     * 发起对象
     */
    private String sendFrom;
    /**
     * 附件路径数组
     */
    private String[] filePaths;
    /**
     * 内嵌图片ID
     */
    private String inlineImgId;
    /**
     * 内嵌图片路径
     */
    private String inlineImgPath;
}

新建EmailService类:

@Autowired
    MailProperties mailProperties;
    @Autowired
    JavaMailSender javaMailSender;

    /**
     *  发送文本邮件
     * @Author mazq
     * @Date 2020/07/22 16:31
     * @Param [email]
     * @return
     */
    public void sendTextMail(EmailDto email) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(email.getSendTo());
        mailMessage.setSubject(email.getSubject());
        mailMessage.setText(email.getContent());
        mailMessage.setFrom(mailProperties.getUsername());
        javaMailSender.send(mailMessage);
    }

junit测试:

@Test
    void testSendTextMail(){
        EmailDto emailDto = new EmailDto();
        emailDto.setSendTo("your_email@qq.com");
        emailDto.setSubject("发送文本邮件");
        emailDto.setContent("测试发送文本邮件!");
        emailService.sendTextMail(emailDto);
    }

在这里插入图片描述

2.5 发送Html格式邮件

 /**
     *  发送Html邮件
     * @Author mazq
     * @Date 2020/07/22 16:31
     * @Param [email]
     * @return
     */
    public void sendHtmlMail(EmailDto email) throws MessagingException {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
        messageHelper.setTo(email.getSendTo());
        messageHelper.setSubject(email.getSubject());
        messageHelper.setText(email.getContent(),true);
        messageHelper.setFrom(mailProperties.getUsername());
        javaMailSender.send(mailMessage);
    }

Junit测试:

@Test
    void testSendHtmlMail() throws MessagingException {
        EmailDto emailDto = new EmailDto();
        emailDto.setSendTo("your_email@qq.com");
        emailDto.setSubject("发送html邮件");
        String html = "<html><head><title>email</title></head><body><h1>测试发送html邮件</h1></body></html>";
        emailDto.setContent(html);
        emailService.sendHtmlMail(emailDto);
    }

在这里插入图片描述

2.6 发送html内嵌图片

2.5介绍了发送html格式的邮件,如果html里要加上图片?具体实现请看下文:

/**
     *  发送html内嵌图片邮件
     * @Author mazq
     * @Date 2020/07/22 16:31
     * @Param [email]
     * @return
     */
    public void sendInLineImgMail(EmailDto email) throws MessagingException {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
        messageHelper.setTo(email.getSendTo());
        messageHelper.setSubject(email.getSubject());
        messageHelper.setText(email.getContent(),true);
        messageHelper.setFrom(mailProperties.getUsername());
        FileSystemResource fileSystemResource = new FileSystemResource(new File(email.getInlineImgPath()));
        messageHelper.addInline(email.getInlineImgId(), fileSystemResource);
        javaMailSender.send(mailMessage);
    }

这边加上图片路径:

@Test
    void testSendInLineImgMail() throws MessagingException {
        String inlineImgPath = "C:\\Users\\Administrator\\Desktop\\007Tv3Vmly1ggxvrzrytij31hc0u047h.jpg";
        String srcId = "img01";
        EmailDto emailDto = new EmailDto();
        emailDto.setSendTo("your_email@qq.com");
        emailDto.setSubject("发送html内嵌图片邮件");
        emailDto.setInlineImgId(srcId);
        emailDto.setInlineImgPath(inlineImgPath);
        String html = "<html><head><title>email</title></head><body><h1>发送html内嵌图片邮件</h1>"+
                "<img src=\'cid:"+ srcId +"\'></img>" +
                "</body></html>";
        emailDto.setContent(html);
        emailService.sendInLineImgMail(emailDto);
    }

测试发送成功:
在这里插入图片描述

2.7 发送模板html邮件

如果发送html邮件,邮件里的内容要动态的,这种可以怎么实现?写html的字符串,然后去发送也是可以,不过如果用模板引擎就可以简洁点,请看代码:

先写个html,引入Thymeleaf模板引擎

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>模板邮件</title>
</head>
<body>
您好,<span th:text="${username}"></span>,欢迎访问我的CSDN博客:
<a href="https://smilenicky.blog.csdn.net/">CSDN链接</a>
</body>
</html>

Junit测试:

@Test
    void testSendTemplateEmail() throws MessagingException {
        Context context = new Context();
        context.setVariable("username", "admin");
        context.setVariable("id", "123456789");
        EmailDto emailDto = new EmailDto();
        emailDto.setSendTo("your_emial@qq.com");
        emailDto.setSubject("发送模板html邮件");
        emailDto.setContent(templateEngine.process("test",context));
        emailService.sendHtmlMail(emailDto);
    }

测试成功,数据是动态的
在这里插入图片描述

2.8 发送Attachment邮件

如果要发送带附件的邮件,怎么实现?请看代码:

/**
     *  发送附件邮件
     * @Author mazq
     * @Date 2020/07/22 16:31
     * @Param [email]
     * @return
     */
    public void sendAttachmentMail(EmailDto email) throws MessagingException {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
        messageHelper.setTo(email.getSendTo());
        messageHelper.setSubject(email.getSubject());
        messageHelper.setText(email.getContent(),true);
        messageHelper.setFrom(mailProperties.getUsername());
        for (String filePath : email.getFilePaths()) {
            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            messageHelper.addAttachment(fileSystemResource.getFilename() , fileSystemResource);
        }
        javaMailSender.send(mailMessage);
    }
 @Test
    void testSendAttachmentMail() throws MessagingException {
        String[] filePaths = new String[]{"C:\\Users\\Administrator\\Desktop\\awrrpt_2_22022_22023.html","C:\\Users\\Administrator\\Desktop\\awr.html"};
        EmailDto emailDto = new EmailDto();
        emailDto.setSendTo("your_email@qq.com");
        emailDto.setSubject("发送附件邮件");
        emailDto.setFilePaths(filePaths);
        String html = "<html><head><title>email</title></head><body><h1>测试发送附件邮件</h1></body></html>";
        emailDto.setContent(html);
        emailService.sendAttachmentMail(emailDto);
    }

在这里插入图片描述

代码例子下载:code download

posted @ 2020-07-22 20:55  smileNicky  阅读(389)  评论(0编辑  收藏  举报