首页 > 其他分享 >Spring Boot 整合邮件服务

Spring Boot 整合邮件服务

时间:2023-05-02 11:44:31浏览次数:34  
标签:String Spring Boot springframework import mail org 邮件

参考教程

首先参考了 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: [email protected] #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: [email protected]
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);
    }

}

标签:String,Spring,Boot,springframework,import,mail,org,邮件
From: https://www.cnblogs.com/seolas/p/17367494.html

相关文章

  • springboot 静态资源导入
    1.根据源码可以看到需要去webjars官网下载jquery的依赖<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>2.2.4</version></dependency>2.读源码 总结: 1.在springboot中可以使用以下五种方式处理静态资源:we......
  • Spring源码:Bean的生命周期(二)
    前言让我们继续讲解Spring的Bean实例化过程。在上一节中,我们已经讲解了Spring是如何将Bean定义加入到IoC容器中,并使用合并的Bean定义来包装原始的Bean定义。接下来,我们将继续讲解Spring的getBean()方法,特别是针对FactoryBean的解析。在getBean()方法中,Spring还支持......
  • springSecurity过滤器之AnonymousAuthenticationFilter
    SpringSecurity提供了匿名登录功能,让我们不登录也能访问。比如/anoy路径及子路径都能匿名访问,配置如下:@ConfigurationpublicclassMySecurityConfigextendsWebSecurityConfigurerAdapter{@Overrideprotectedvoidconfigure(HttpSecurityhttp)throwsException......
  • SpringBoot高频面试题
    Springboot的优点内置servlet容器,不需要在服务器部署tomcat。只需要将项目打成jar包,使用java-jarxxx.jar一键式启动项目SpringBoot提供了starter,把常用库聚合在一起,简化复杂的环境配置,快速搭建spring应用环境可以快速创建独立运行的spring项目,集成主流框架准生产环境的......
  • Spring事务
    事务作用:在数据层保障一系列的数据库操作同成功同失败Spring事务作用:在数据层或业务层保障一系列的数据库操作,同成功同失败案例:银行账户转账1.在业务层接口上添加Spring事务管理2.设置事务管理器3.开启注解式事务驱动事务角色事务管理员:发起事务方,在Spring中通常指代业务......
  • Java教程:Springboot项目如何使用Test单元测试
    今天早上来公司领导突然分配了任务,就是简单的测试一下实体的添加修改功能,要使用到Juntil单元测试,目前使用springboot项目,jpa,maven管理,回忆起曾经用到过@Test注解,于是开始唰唰唰的写起了测试咧,然鹅,一顿报错,依赖无法注入,空指针,乱七八糟的一大通,无奈开始借助百度,终于实现了单元测试,......
  • SpringBoot项目使用 validation进行数据校验
    validation进行数据校验@Validated注解和@Valid注解都是SpringFramework中用于数据校验的注解,但它们有以下几点区别:所在包路径不同:@Valid注解位于javax.validation.constraints包下,而@Validated注解位于org.springframework.validation.annotation包下。支持......
  • Springboot @Test 给Controller接口 写 单元测试
    Springboot@Test给Controller接口写单元测试https://blog.csdn.net/qq_35387940/article/details/129140984?spm=1001.2101.3001.6650.8&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-8-129140984-blog-103569814.235%5Ev32......
  • Spring源码:bean的生命周期(一)
    前言本节将正式介绍Spring源码细节,将讲解Bean生命周期。请注意,虽然我们不希望过于繁琐地理解Spring源码,但也不要认为Spring源码很简单。在本节中,我们将主要讲解Spring5.3.10版本的源代码。如果您看到的代码与我讲解的不同,也没有关系,因为其中的原理和业务逻辑基本相同。为了更好......
  • java基于springboot的毕业生信息招聘平台、高校学生招聘管理系统、招聘管理系统,附源码
    1、项目介绍毕业生信息招聘平台的功能如下:管理管理员;首页、个人中心、企业管理、空中宣讲会管理、招聘岗位管理、毕业生管理、个人简历管理、求职信息管理、信息咨询管理、岗位应聘管理、线上面试管理、面试回复管理、试卷管理、试题管理、管理员管理、论坛管理、系统管理、考试......