使用springboot发送邮件

简述

最近在写关于发短信相关的模块,分的任务中有一个发邮件的功能
之前没写过相关的,于是收集了相关资料,完成功能后,这里以以QQ邮箱为例写了这篇博文。

在日常工作开发中,发送邮件功能有时需要我们去开发使用,这里首先介绍以下与发送接受邮件相关的一些协议:
发送邮件:SMPT、MIME,是一种基于"推"的协议,通过SMPT协议将邮件发送至邮件服务器,MIME协议是对SMPT协议的一种补充,如发送图片附件等
接收邮件:POP、IMAP,是一种基于"拉"的协议,收件人通过POP协议从邮件服务器拉取邮件
嘿嘿,讲的太简单了,具体资料大家可以上网或看书来进一步了解,很多的哦

使用SpringBoot发送邮件

使用SpirngBoot发送邮件,首先需要引入mail依赖

pom文件

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

然后在配置文件application.properties中加入相关配置信息
#这里

配置文件 application.properties

#QQ邮箱服务器
spring.mail.host=smtp.qq.com
#你的QQ邮箱账户
spring.mail.username=yourAccount@qq.com
#你的QQ邮箱第三方授权码
spring.mail.password=yourPassword
#编码类型
spring.mail.default-encoding=UTF-8

你写到yml中也行 ,格式会发生变化,这里就不一一表出。

application.properties中部分参数

spring.mail.password的参数如何获取:
此处参数名为第三方授权码
开启邮箱第三方支持以及获取授权码(以QQ邮箱为例)
打开QQ邮箱,点击设置
在这里插入图片描述选择账户,并下拉找到
在这里插入图片描述
在这里插入图片描述开启第一个或前两个,然后点击开启
之后可能会需要发短信验证
验证成功后 页面会显示第三方授权码

controller层

controller层自己调一下就完事。

service层

public interface MailService {
    /**
     * 发送普通文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);
    /**
     * 发送HTML邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容(可以包含<html>等标签)
     */
    void sendHtmlMail(String to, String subject, String content);
    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件路径
     */
    void sendAttachmentMail(String to, String subject, String content, String filePath);
    /**
     * 发送带图片的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 文本
     * @param rscPath 图片路径
     * @param rscId 图片ID,用于在<img>标签中使用,从而显示图片
     */
    void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
    
}

serviceImpl层

@Service
public class MailServiceImpl implements MailService {
    @Value("${spring.mail.username}")
    //使用@Value注入application.properties中指定的用户名
    private String from;
    
    @Autowired
    //用于发送文件
    private JavaMailSender mailSender;

【发送普通邮件】
我们这里的普通邮件是指最为普通的纯文本邮件

    public void sendSimpleMail(String to, String subject, String content) {
        
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(from);//发信人
        
        mailSender.send(message);
    }

【发送HTML文件】
HTML文件就是指在文件内容中可以添加等标签,收件人收到邮件后显示内容也和网页一样,比较丰富多彩

    public void sendHtmlMail(String to, String subject, String content) {
        
        logger.info("发送HTML邮件开始:{},{},{}", to, subject, content);
        //使用MimeMessage,MIME协议
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支持html
            mailSender.send(message);
            logger.info("发送HTML邮件成功");
        } catch (MessagingException e) {
            logger.error("发送HTML邮件失败:", e);
        }    
    }

【发送带附件的邮件】
带附件的邮件在HTML邮件上添加一些参数即可

    public void sendAttachmentMail(String to, String subject, String content, String filePath) {
        
        logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, filePath);
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件,如附件,图片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件  
            mailSender.send(message);
            logger.info("发送带附件邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带附件邮件失败", e);
        }
    }

【发送带图片的邮件】
带图片即在正文中使用标签,并设置我们需要发送的图片,也是在HTML基础上添加一些参数

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        
        logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        try {
            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("发送带图片邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带图片邮件失败", e);
        }
    }

测试

使用SpirngBoot Junit Test进行简单测试

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {

    @Autowired
    private MailService mailService;
    @Autowired
    private TemplateEngine templateEngine;
    
    /**
     * 发送简单纯文本邮件
     */
    @Test
    public void sendSimpleMail() {
        mailService.sendSimpleMail("receiver@email.com", "发送邮件测试", "大家好,这是我用springboot进行发送邮件测试");
    }
    
    /**
     * 发送HTML邮件
     */
    @Test
    public void sendHtmlMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件" + "</font></h3></body></html>";
        mailService.sendHtmlMail("receiver@email.com", "发送邮件测试", content);
    }
    
    /**
     * 发送带附件的邮件
     */
    @Test
    public void sendAttachmentMail() {
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件,有附件哦" + "</font></h3></body></html>";
        String filePath = "your file path";
        mailService.sendAttachmentMail("receiver@email.com", "发送邮件测试", content, filePath);
    }
    
    /**
     * 发送带图片的邮件
     */
    @Test
    public void sendInlineResourceMail() {
        String rscPath = "your picture path";
        String rscId = "001";
        String content = "<html><body><h3><font color=\"red\">" + "大家好,这是springboot发送的HTML邮件,有图片哦" + "</font></h3>"
                         + "<img src=\'cid:" + rscId + "\'></body></html>";
        mailService.sendInlineResourceMail("receiver@email.com", "发送邮件测试", content, rscPath, rscId);
    }

}

如何发送模板邮件?

这里我们提一下很常见的模板邮件,比如说我们注册账户,登录认证所收到的邮件即为模板邮件,特点就是内容不变,只是一些特点信息比如说验证码、认证链接等是动态变化的。
以Thymeleaf模板引擎为例来讲解(具体语法自行了解)
在template文件夹下创建emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件模板</title>
</head>
<body>
您好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!<br>
<a href="#" th:href="@{http://www.bestbpf.com/register/{id}(id=${id})}">激活账户</a>
</body>
</html>

在模板页面中,id是动态变化的,需要我们传参设置,其实就是传参后,将页面解析为HTML字符串,作为我们邮件发送的主体内容
【测试】

    /**
     * 指定模板发送邮件
     */
    @Test
    public void testTemplateMail() {
        //向Thymeleaf模板传值,并解析成字符串
        Context context = new Context();
        context.setVariable("id", "001");
        String emailContent = templateEngine.process("emailTemplate", context);
        
        mailService.sendHtmlMail("receiver@email.com", "这是一个模板文件", emailContent);
    }

有疑问可以评论,看到后会回复

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值