惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
V
V2EX
Martin Fowler
Martin Fowler
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
博客园 - 【当耐特】
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
K
Kaspersky official blog
Security Latest
Security Latest
H
Help Net Security
博客园_首页
美团技术团队
Spread Privacy
Spread Privacy
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
G
Google Developers Blog
NISL@THU
NISL@THU
爱范儿
爱范儿
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
I
InfoQ
The Cloudflare Blog
F
Full Disclosure
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

博客园 - smileNicky

魔珐星云SDK实战测评:重构数字人交互的底层逻辑 Ling Studio 深度体验:当万亿参数大模型遇上AI原生IDE,编程范式正在重构 魔珐星云SDK实战测评:从0到1搭建会“思考+互动”的智能数字人客服应用 云电脑玩转 CANN 全攻略:从环境搭建到创新应用落地 SpringBoot系列之集成EasyExcel实现百万级别的数据导入导出实践 分布式ID生成方案总结整理 并发编程系列之如何正确使用线程池? Spring Cloud Alibaba系列之分布式服务组件Dubbo Spring5.0源码学习系列之事务管理概述 Spring5.0源码学习系列之Spring AOP简述 利用ADB命令强制卸载oppo自带浏览器 SpringBoot系列之从入门到精通系列教程 SpringCloud系列之API网关(Gateway)服务Zuul SpringCloud系列之服务容错保护Netflix Hystrix SpringCloud系列之客户端负载均衡Netflix Ribbon SpringCloud系列之使用Feign进行服务调用 SpringCloud系列使用Eureka进行服务治理 Spring Security系列之极速入门与实践教程 SpringBoot系列之actuator监控管理极速入门与实践 SpringBoot系列之IDEA项目中设置热部署教程
SpringBoot系列之发送邮件极速入门与实践
smileNicky · 2020-07-22 · via 博客园 - smileNicky

一、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:
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200722165731985.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0MjczOTE=,size_16,color_FFFFFF,t_70)
网易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);
    }

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200722170317319.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0MjczOTE=,size_16,color_FFFFFF,t_70)

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);
    }

测试发送成功:
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200722172155743.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0MjczOTE=,size_16,color_FFFFFF,t_70)

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);
    }

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20200722170951135.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0MjczOTE=,size_16,color_FFFFFF,t_70)

代码例子下载:code download