发送邮件
Spring Boot 发送邮件指南
在 Spring Boot 中发送邮件非常简单,主要使用 Spring 的 JavaMailSender
接口。以下是完整的实现步骤:
- 添加依赖
首先,在 pom.xml
中添加邮件相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 配置邮件服务器
在 application.properties
或 application.yml
中配置邮件服务器信息:
# SMTP服务器配置
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-password
spring.mail.protocol=smtp
# TLS配置
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
或者 YAML 格式:
spring:
mail:
host: smtp.example.com
port: 587
username: your-email@example.com
password: your-password
protocol: smtp
properties:
mail:
smtp:
auth: true
starttls:
enable: true
- 创建邮件服务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
/**
* 发送简单文本邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param text 邮件内容
*/
public void sendSimpleEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
/**
* 发送HTML格式邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param htmlContent HTML内容
* @throws MessagingException
*/
public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // true表示发送HTML格式
mailSender.send(message);
}
/**
* 发送带附件的邮件
* @param to 收件人邮箱
* @param subject 邮件主题
* @param text 邮件内容
* @param attachmentPath 附件路径
* @param attachmentName 附件显示名称
* @throws MessagingException
*/
public void sendEmailWithAttachment(String to, String subject, String text,
String attachmentPath, String attachmentName)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
// 添加附件
FileSystemResource file = new FileSystemResource(new File(attachmentPath));
helper.addAttachment(attachmentName, file);
mailSender.send(message);
}
}
- 使用邮件服务
在控制器或其他服务中注入并使用邮件服务:
@RestController
@RequestMapping("/api/email")
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/send-simple")
public String sendSimpleEmail() {
emailService.sendSimpleEmail(
"recipient@example.com",
"测试邮件",
"这是一封测试邮件,来自Spring Boot应用。"
);
return "简单邮件已发送";
}
@GetMapping("/send-html")
public String sendHtmlEmail() throws MessagingException {
String htmlContent = "<h1>HTML邮件测试</h1>" +
"<p style='color:blue;'>这是一封HTML格式的测试邮件</p>" +
"<a href='https://example.com'>点击访问示例网站</a>";
emailService.sendHtmlEmail(
"recipient@example.com",
"HTML测试邮件",
htmlContent
);
return "HTML邮件已发送";
}
}
- 高级配置
使用模板引擎发送邮件
结合 Thymeleaf 发送模板邮件:
- 添加 Thymeleaf 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 创建模板邮件服务方法:
@Service
public class EmailService {
// ... 其他代码
@Autowired
private TemplateEngine templateEngine;
/**
* 使用Thymeleaf模板发送邮件
*/
public void sendTemplateEmail(String to, String subject, Map<String, Object> variables)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// 处理邮件模板
Context context = new Context();
context.setVariables(variables);
String emailContent = templateEngine.process("email-template", context);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(emailContent, true);
mailSender.send(message);
}
}
- 创建模板文件
resources/templates/email-template.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">邮件标题</title>
</head>
<body>
<h1 th:text="${header}">邮件头部</h1>
<p th:text="${content}">邮件内容</p>
<p>当前时间: <span th:text="${#dates.format(#dates.createNow(), 'yyyy-MM-dd HH:mm')}"></span></p>
</body>
</html>
- 测试邮件发送
可以创建一个测试类来验证邮件发送功能:
@SpringBootTest
public class EmailServiceTest {
@Autowired
private EmailService emailService;
@Test
public void testSendSimpleEmail() {
emailService.sendSimpleEmail(
"recipient@example.com",
"测试邮件",
"这是一封测试邮件"
);
}
@Test
public void testSendHtmlEmail() throws MessagingException {
String htmlContent = "<h1>测试HTML邮件</h1><p>这是一封HTML格式的测试邮件</p>";
emailService.sendHtmlEmail(
"recipient@example.com",
"HTML测试邮件",
htmlContent
);
}
}
注意事项
- 确保你的邮件服务器配置正确,特别是用户名、密码和SMTP设置
- 对于Gmail等邮箱,可能需要开启”允许不够安全的应用”或生成应用专用密码
- 生产环境中建议将密码等敏感信息放在环境变量或配置中心
- 对于大量邮件发送,考虑使用异步方式或邮件队列
- 注意处理邮件发送异常,避免影响主业务流程
异步发送邮件
为了提高性能,可以使用异步方式发送邮件:
- 在主类上添加
@EnableAsync
注解:
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 修改邮件服务方法:
@Async
public void sendSimpleEmailAsync(String to, String subject, String text) {
sendSimpleEmail(to, subject, text);
}
这样调用 sendSimpleEmailAsync
方法时,邮件发送将在后台线程中执行,不会阻塞主线程。
推荐文章: