SpringBoot发送邮箱总结

前言

虽然现在登录都是手机验证码发送,但是工作当中也有些业务场景需要发送邮箱。本文来介绍邮箱发送的使用和原理,做一些有用的总结。
参考:
1.https://www.jianshu.com/p/59d15b357201
2.https://www.cnblogs.com/sun2020/p/13961554.html

1.简单的一些总结:

动作说明备注
发送邮件SMPT、MIME,是一种基于"推"的协议,通过SMPT协议将邮件发送至邮件服务器,MIME协议是对SMPT协议的一种补充,如发送图片附件等SMTP 协议全称为 Simple Mail Transfer Protocol,译作简单邮件传输协议
接收邮件POP、IMAP,是一种基于"拉"的协议,收件人通过POP协议从邮件服务器拉取邮件

个人总结:
使用qq邮箱进行发送需要开启POP3和SMTP协议,需要获得邮件服务器的授权码。具体的配置过程可参考上面的链接。

2.SpringBoot发送邮件:

2.1添加依赖:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
2.2账号配置;
#发送邮箱地址
#这里以QQ邮箱为例
#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

非qq邮箱注意端口和地址:

mail.address=xxx@xxx.com
spring.mail.host= xxx
spring.mail.username=xxx
spring.mail.password=xxx
spring.mail.port=587

重要说明:mail.address和spring.mail.username在qq邮箱里面是相同的,但是在公司的邮箱可以相同可以不相同,大部分是不相同的,大部分公司里的邮箱服务账号是没有后缀的,这个是采坑的地方,需要注意。

2.3具体代码实现;

这里github上面有一个很不错的demo:
https://github.com/BestbpF/springboot-mail
使用:

    private final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    //这里是重点需要区分是qq邮箱和企业邮箱
    @Value("${spring.mail.username}")
    //使用@Value注入application.properties中指定的用户名
    private String from;
    
    @Autowired
    //用于发送文件服务
    private JavaMailSender mailSender;

发送服务的接口定义:

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);
    
}
2.3.1发送的普通文本邮件:
    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);
    }
2.3.2发送的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);
        }    
    }

2.3.3发送的带附件文件:
    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);
        }

        
    }
2.3.4发送的带图片的邮件:
    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);
        }
    }
2.3.5发送模板邮件:

模板邮件发送其实是基于html的模板发送,需要引入依赖:

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

2.在template文件夹下创建emailTemplate.html:
模板1:

<!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>

模板2:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>xx</title>
</head>
<body>
亲爱的用户您好:<br>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您本次的验证随机码为:</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<label th:text="${checkCode}"></label>
</p> <br>
请在验证页面指定位置输入随机码,进行验证,有效期为15分钟。
<br><br><br>
此邮件为xxxx育自动发送的电子邮件,无需回复!
</body>
</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);
    }

其他单元测试:

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

}

结尾

上面就是整个的发送邮件的总结,其中一部分是参考的链接当中的内容,然后加入了自己的采坑总结,其中本文介绍的虽然是springboot发送邮件的流程,但是其实spring-boot-starter-mail依赖包下面也是相等于使用的javax.mail进行的发送邮件服务,其中的流程就是通过账号密码进行认证,然后认证完以后创建socket,进行发送,整个过程因为涉及到服务器的认证和socket的链接创建,所以有的时候比较耗时,实际开发当中到发送邮件那个方法采用异步@Async进行发送就可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot开发中,我们经常会用到邮件发送功能,但是当需要发送大量邮件时,单线程发送邮件的效率显然是低下的,这时候我们就需要使用队列来提高效率。本文将介绍如何使用SpringBoot整合mail队列来发送大量邮件。 ## 1. 配置邮件参数 在application.properties文件中配置邮件参数: ``` spring.mail.host=smtp.qq.com spring.mail.username=your-email@qq.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.properties.mail.smtp.timeout=5000 ``` ## 2. 定义邮件模板 在resources/templates目录下创建邮件模板,例如: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>Hello, ${name}!</h1> <p>这是一封测试邮件。</p> </body> </html> ``` ## 3. 创建Mail对象 创建Mail对象,包含邮件的基本信息,例如:收件人、主题、内容等。 ``` @Data public class Mail { //收件人 private String to; //主题 private String subject; //内容 private String content; //邮件模板 private String template; //邮件模板参数 private Map<String, Object> templateModel; } ``` ## 4. 创建MailService 创建MailService,负责发送邮件。 ``` @Service public class MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender javaMailSender; /** * 发送邮件 * * @param mail 邮件对象 */ public void send(Mail mail) { try { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(javaMailSender.getUsername()); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); if (mail.getTemplate() != null) { Context context = new Context(); context.setVariables(mail.getTemplateModel()); String content = TemplateUtil.processTemplateIntoString(TemplateUtil.getTemplate(mail.getTemplate()), context); helper.setText(content, true); } else { helper.setText(mail.getContent(), true); } javaMailSender.send(message); logger.info("发送邮件成功:{}", mail.getTo()); } catch (Exception e) { logger.error("发送邮件失败:{}", mail.getTo(), e); } } } ``` ## 5. 创建MailQueue 创建MailQueue,用于存放待发送的邮件。 ``` @Component public class MailQueue { private Queue<Mail> queue = new LinkedBlockingQueue<>(); /** * 添加邮件到队列 * * @param mail 邮件对象 */ public void add(Mail mail) { queue.offer(mail); } /** * 获取队列大小 * * @return 队列大小 */ public int size() { return queue.size(); } /** * 获取队列中的邮件对象 * * @return 邮件对象 */ public Mail get() { return queue.poll(); } } ``` ## 6. 创建MailSender 创建MailSender,用于从MailQueue中获取待发送的邮件并发送。 ``` @Component public class MailSender implements Runnable { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MailQueue mailQueue; @Autowired private MailService mailService; @Override public void run() { while (true) { try { if (mailQueue.size() > 0) { Mail mail = mailQueue.get(); if (mail != null) { mailService.send(mail); } } Thread.sleep(1000); } catch (Exception e) { logger.error("发送邮件失败", e); } } } } ``` ## 7. 创建MailConfig 创建MailConfig,将MailSender配置为后台线程,并启动。 ``` @Configuration @EnableScheduling public class MailConfig { @Autowired private MailSender mailSender; /** * 启动MailSender */ @Scheduled(initialDelay = 5000, fixedDelay = 1000) public void startMailSender() { new Thread(mailSender).start(); } } ``` ## 8. 使用MailQueue发送邮件 使用MailQueue发送邮件,例如: ``` @Autowired private MailQueue mailQueue; public void sendMail() { Mail mail = new Mail(); mail.setTo("test@qq.com"); mail.setSubject("测试邮件"); mail.setTemplate("mail/test.html"); Map<String, Object> templateModel = new HashMap<>(); templateModel.put("name", "SpringBoot"); mail.setTemplateModel(templateModel); mailQueue.add(mail); } ``` ## 9. 总结 通过使用SpringBoot整合mail队列,可以提高发送大量邮件的效率。我们可以将待发送的邮件添加到MailQueue中,然后MailSender从MailQueue中获取待发送的邮件并发送。这样就能够实现异步发送邮件,并提高发送邮件的效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值