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

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - smileNicky

Ling Studio 深度体验:当万亿参数大模型遇上AI原生IDE,编程范式正在重构 - smileNicky 魔珐星云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:
在这里插入图片描述
网易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