參考教程
首先參考了 Spring Boot整合郵件配置,這篇文章寫的很好,按照上面的操作一步步走下去就行了。
遇到的問題
版本配置
然后因為反復配置版本很麻煩,所以參考了 如何統(tǒng)一引入 Spring Boot 版本?。
FreeMarker
在配置 FreeMarker 時,發(fā)現(xiàn)找不到 FreeMarkerConfigurer
類,參考了 springboot整合Freemark模板(詳盡版) 發(fā)現(xiàn)要添加 web 模塊。
測試注解
在使用測試類的時候,我只添加了 @SpringBootTest
注解,報空指針,參考了 測試類的@RunWith與@SpringBootTest注解 發(fā)現(xiàn)還要添加 @RunWith(SpringRunner.class)
注解。文章來源:http://www.zghlxwxcb.cn/news/detail-431511.html
實踐結(jié)果
代碼地址
完成的項目地址。文章來源地址http://www.zghlxwxcb.cn/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 #發(fā)送郵件服務器
username: xxx@qq.com #QQ郵箱
password: xxx #客戶端授權(quán)碼
protocol: smtp #發(fā)送郵件協(xié)議
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 # 緩存配置 開發(fā)階段應該配置為false 因為經(jīng)常會改
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官方提供的集成郵件服務的實現(xiàn)類,目前是Java后端發(fā)送郵件和集成郵件服務的主流工具。
@Resource
private JavaMailSender mailSender;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
// 從配置文件中注入發(fā)件人的姓名
@Value("${spring.mail.username}")
private String fromEmail;
/**
* 發(fā)送文本郵件
*
* @param to 收件人
* @param subject 標題
* @param content 正文
*/
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail); // 發(fā)件人
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
/**
* 發(fā)送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);
//第二個參數(shù):格式是否為html
helper.setText(content, true);
mailSender.send(message);
}
/**
* 發(fā)送freemarker郵件
*/
public void sendTemplateMail(String to, String subject, String templatehtml) throws Exception {
// 獲得模板
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatehtml);
// 使用Map作為數(shù)據(jù)模型,定義屬性和值
Map<String, Object> model = new HashMap<>();
model.put("myname", "Seolas");
// 傳入數(shù)據(jù)模型到模板,替代模板中的占位符,并將模板轉(zhuǎn)化為html字符串
String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
// 該方法本質(zhì)上還是發(fā)送html郵件,調(diào)用之前發(fā)送html郵件的方法
this.sendHtmlMail(to, subject, templateHtml);
}
/**
* 發(fā)送帶附件的郵件
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//要帶附件第二個參數(shù)設(shè)為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, "普通文本郵件", "普通文本郵件內(nèi)容");
}
@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);
}
}
到了這里,關(guān)于Spring Boot 整合郵件服務的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!