本篇文章提供了一个详细的教程,在Spring Boot项目中如何整合并使用邮件服务来发送包含自定义内容的模板邮件,附有完整示例代码。
在SpringBoot项目中整合Mail以实现发送模板邮件的示例代码如下:
首先,在项目的`pom.xml`文件中添加依赖:
```xml
org.springframework.boot
spring-boot-starter-mail
org.thymeleaf.extras
thymeleaf-extras-springsecurity5
```
接下来,在`application.yml`中配置邮箱服务器信息:
```yaml
spring:
mail:
host: smtp.163.com # 邮件服务器地址,以网易为例
username: yourEmail@163.com # 发送邮件的账号
password: yourPasswordOrVCode # 密码或授权码
thymeleaf:
prefix: classpath:/templates/ # 模板文件存放路径
```
创建一个Java类用于发送模板邮件:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender; // 引入JavaMailSender接口
public void sendTemplateEmail(String to, String subject) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
// 加载并渲染模板
Context context = new Context();
context.setVariable(variableName, 变量值);
String htmlContent = templateEngine.process(templateFileName, context);
helper.setText(htmlContent, true);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
mailSender.send(message);
}
}
```
在上述代码中,`sendTemplateEmail()`方法用于发送包含模板内容的邮件。需要根据实际情况设置收件人邮箱地址、主题以及Thymeleaf模板文件名。
最后,在HTML或Thymeleaf模板文件(如`src/main/resources/templates/templateFileName.html`)中编写邮件的内容:
```html
示例标题
Hello, 变量值!
```
以上就是基于SpringBoot整合Mail并发送模板邮件的基本步骤和示例代码。根据实际需求进行适当调整即可实现自定义功能。