SpringBoot整合邮件服务

博客 分享
0 131
优雅殿下
优雅殿下 2023-05-02 11:54:42
悬赏:0 积分 收藏

Spring Boot 整合邮件服务

参考教程

首先参考了 Spring Boot整合邮件配置,这篇文章写的很好,按照上面的操作一步步走下去就行了。

遇到的问题

版本配置

然后因为反复配置版本很麻烦,所以参考了 如何统一引入 Spring Boot 版本?

FreeMarker

在配置 FreeMarker 时,发现找不到 FreeMarkerConfigurer 类,参考了 springboot整合Freemark模板(详尽版) 发现要添加 web 模块。

测试注解

在使用测试类的时候,我只添加了 @SpringBootTest 注解,报空指针,参考了 测试类的@RunWith与@SpringBootTest注解 发现还要添加 @RunWith(SpringRunner.class) 注解。

实践结果

代码地址

完成的项目地址

核心代码

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fun.seolas</groupId>
    <artifactId>spring-boot-mail-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
application.yaml
spring:
  mail:
    host: smtp.qq.com #发送邮件服务器
    username: xxx@qq.com #QQ邮箱
    password: xxx #客户端授权码
    protocol: smtp #发送邮件协议
    properties.mail.smtp.auth: true
    properties.mail.smtp.port: 465 #端口号465或587
    properties.mail.display.sendmail: aaa #可以任意
    properties.mail.display.sendname: bbb #可以任意
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true #开启SSL
    default-encoding: utf-8
  freemarker:
    cache: false # 缓存配置 开发阶段应该配置为false 因为经常会改
    suffix: .html # 模版后缀名 默认为ftl
    charset: UTF-8 # 文件编码
    template-loader-path: classpath:/templates/  # 存放模板的文件夹,以resource文件夹为相对路径

my:
  toemail: xx@xx.com
MailService.java
package fun.seolas;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailService {
    // Spring官方提供的集成邮件服务的实现类,目前是Java后端发送邮件和集成邮件服务的主流工具。
    @Resource
    private JavaMailSender mailSender;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    // 从配置文件中注入发件人的姓名
    @Value("${spring.mail.username}")
    private String fromEmail;

    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 标题
     * @param content 正文
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail); // 发件人
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 发送html邮件
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        //注意这里使用的是MimeMessage
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromEmail);
        helper.setTo(to);
        helper.setSubject(subject);
        //第二个参数:格式是否为html
        helper.setText(content, true);
        mailSender.send(message);
    }

    /**
     * 发送freemarker邮件
     */
    public void sendTemplateMail(String to, String subject, String templatehtml) throws Exception {
        // 获得模板
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatehtml);
        // 使用Map作为数据模型,定义属性和值
        Map<String, Object> model = new HashMap<>();
        model.put("myname", "Seolas");
        // 传入数据模型到模板,替代模板中的占位符,并将模板转化为html字符串
        String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        // 该方法本质上还是发送html邮件,调用之前发送html邮件的方法
        this.sendHtmlMail(to, subject, templateHtml);
    }

    /**
     * 发送带附件的邮件
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        //要带附件第二个参数设为true
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromEmail);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }
}

MailTest.java
package fun.seolas;

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

import javax.mail.MessagingException;

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

    @Autowired
    private MailService mailService;

    @Value("${my.toemail}")
    private String toemail;

    @Test
    public void test01() {
        mailService.sendSimpleMail(toemail, "普通文本邮件", "普通文本邮件内容");
    }

    @Test
    public void test02() throws MessagingException {
        mailService.sendHtmlMail(toemail, "一封html测试邮件",
                "<div style=\"text-align: center;position: absolute;\" >\n"
                        + "<h3>\"一封html测试邮件\"</h3>\n"
                        + "<div>一封html测试邮件</div>\n"
                        + "</div>");
    }

    @Test
    public void test3() throws Exception {
        mailService.sendTemplateMail(toemail, "基于模板的html邮件", "freemarkertemp.html");
    }

    @Test
    public void test04() throws MessagingException {
        String filePath = "C:\\Users\\Julia\\Downloads\\测试.txt";
        mailService.sendAttachmentsMail(toemail, "带附件的邮件", "邮件中有附件", filePath);
    }

}
posted @ 2023-05-02 11:28  seolas  阅读(5)  评论(0编辑  收藏  举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2012 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员