Spring Boot 整合邮件服务

这篇具有很好参考价值的文章主要介绍了Spring Boot 整合邮件服务。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

参考教程

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

遇到的问题

版本配置

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

FreeMarker

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

测试注解

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

实践结果

代码地址

完成的项目地址。文章来源地址https://www.toymoban.com/news/detail-431511.html

核心代码

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

}

到了这里,关于Spring Boot 整合邮件服务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 论如何本地搭建个人hMailServer邮件服务远程发送邮件无需域名公网服务器?

    🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页 ——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文并茂🦖生动形象🐅简单易学!欢迎大家来踩踩~🌺 🌊 《IDEA开发秘籍专栏》 🐾 学会IDEA常用操作,工作效率翻倍~💐 🌊 《100天精通Golang(基础

    2024年01月24日
    浏览(45)
  • Mail 邮件服务

    ~ Postfix ~   sdskill.com 的邮件发送服务器 ~~   支持smtps(465)协议连接,使用Rserver颁发的证书,证书路径/CA/cacert.pem ~    创建邮箱账户“user1~user99”(共99个用户),密码为Chinaskill20!; ~    Dovecot ~    sdskill.com 的邮件接收服务器; ~    支持imaps(993)协议连接,使用Rserver颁发

    2023年04月26日
    浏览(32)
  • 一、Postfix[安装与配置、smtp认证、Python发送邮件以及防垃圾邮件方法、使用腾讯云邮件服务]

    Debian 11 apt install postfix 解释:搭建真实的邮件服务器需要在DNS提供商那里配置下面的dns 配置A记录 mail.www.com - 1.x.x.x 配置MX记录 www.com - mail.www.com 解释:按照上面的配置通常邮件格式就是 admin@www.com 其通过www.com的MX记录找到mail.www.com再通过其A记录来找到对应服务器完成通讯 解

    2024年02月15日
    浏览(39)
  • 【服务器】搭建hMailServer 服务实现远程发送邮件

    hMailServer 是一个邮件服务器,通过它我们可以搭建自己的邮件服务,通过cpolar内网映射工具即可实现远程发送邮件,不需要使用公网服务器,不需要域名,而且邮件账号名称可以自定义. 下面以windows 10系统为环境,介绍使用方法: 1. 安装hMailServer 进入官方下载:https://www.hmailserver.com/do

    2024年02月10日
    浏览(33)
  • 电子邮件服务器

    目录 一、相关知识 二、邮件服务器种类 三、邮件传输协议 四、DNS中的MX记录 五、电子邮件系统工作原理 六、配置文件相关参数 七、邮件服务器配置案例 7.1设置用户别名邮箱 7.2空壳邮件服务器 一、相关知识 1、电子邮箱系统三个组成部分 MUA(telnet):邮件用户代理。主要用

    2024年02月10日
    浏览(51)
  • 【服务端】CentOS Linux 7 搭建邮件服务器

    参考:CentOS7搭建简单的邮件服务器 - 秋夜雨巷 - 博客园 (cnblogs.com) 在 CentOS7 中搭建邮件服务器,给QQ邮箱发邮件。简单记录一次搭建过程。 目录 前言 一、基础环境准备 二、配置域名解析 1. 登录阿里云 三、安装邮件服务 1. 登录主机,配置yum源(配置阿里云yum源步骤略) 2

    2024年01月22日
    浏览(47)
  • 邮件服务器配置和管理

    一台安装好的DNS服务器,ip为192.168.1.201 一台邮件服务器,192.168.1.224 一台客户端,192.168.1.249,dnsIP为192.168.1.201 都是wmnet1,使其能互相ping通 1.打开DNS服务器,新建主机 把邮件服务器的主机添加上去,使得客户端可以通过域名找到邮件服务器 1.用实体机进入官网https://www.winma

    2024年03月19日
    浏览(44)
  • Spring Schedule:Spring boot整合Spring Schedule实战讲解定时发送邮件的功能

    🎉🎉 欢迎光临,终于等到你啦 🎉🎉 🏅我是 苏泽 ,一位对技术充满热情的探索者和分享者。🚀🚀 🌟持续更新的专栏 《Spring 狂野之旅:从入门到入魔》 🚀 本专栏带你从Spring入门到入魔   这是苏泽的个人主页可以看到我其他的内容哦👇👇 努力的苏泽 http://suzee.blog.

    2024年03月14日
    浏览(96)
  • 使用CentOS 7配置邮件服务-第四篇

    在上一章我们配置主和从服务器的DNS域名解析,这一章我们配置使用CentOS 7配置邮件服务 要求: 1、两台邮件服务器IP地址分别为192.168.1.学号及192.168.0.199 2、 两台邮件服务器域名为学生姓名。例如mail.zhangsan.com 及mail.zs.com。 3、在DNS服务器配置两台服务器的域名。 4、配置完成

    2024年02月12日
    浏览(26)
  • 快速备份邮件到新服务器

    需求场景 自建邮局后,遇到了意料中的问题:迁移邮件到新邮局,即把原来邮箱里的邮件全部复制到新邮箱。 工具介绍 imapsync是一款强大的工具,用于同步两个邮件服务器之间的数据。它支持IMAP协议,可以轻松地将邮件、文件夹、邮件标记为已读/已删除等。使用imapsync,可

    2024年02月12日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包