在 Spring Boot 2 中发送邮件,主要依赖于 spring-boot-starter-mail 模块。它底层封装了 JavaMailSender,使得发送邮件变得非常简单。
以下是详细的步骤和代码示例:
1. 添加 Maven 依赖
首先,在你的 pom.xml 文件中添加 spring-boot-starter-mail 依赖。
xml
编辑
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 配置邮件服务器 (application.properties 或 application.yml)
你需要在配置文件中提供 SMTP 服务器的相关信息。以下以 QQ 邮箱为例,你需要替换成你自己的邮箱和授权码。
application.properties:
properties
编辑
# SMTP 服务器地址 (QQ邮箱)
spring.mail.host=smtp.qq.com
# 发送方邮箱
spring.mail.username=your-email@qq.com
# 邮箱密码或更安全的授权码
spring.mail.password=your-app-password
# 协议
spring.mail.protocol=smtp
# 端口号 (SSL)
spring.mail.port=465
# 其他属性
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# 开启 SSL
spring.mail.properties.mail.smtp.ssl.enable=true
application.yml:
yaml
编辑
spring:
mail:
host: smtp.qq.com
username: your-email@qq.com
password: your-app-password # 这里填写你的应用授权码
protocol: smtp
port: 465
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
ssl:
enable: true
重要提示:
- 关于密码: 对于大多数现代邮箱(如 QQ、网易、Gmail),你不应该直接使用你的登录密码。你需要在邮箱设置中开启“POP3/SMTP”服务,并生成一个“应用专用密码”或“授权码”,然后将这个授权码填入
spring.mail.password。 - 关于端口和协议: 不同邮箱的 SMTP 服务器配置不同。
465端口通常用于 SSL 加密,而587端口用于 STARTTLS 加密。请根据你的邮箱服务商的文档进行配置。
3. 创建一个 Service 类来发送邮件
创建一个服务类,注入 JavaMailSender,并编写发送邮件的方法。
java
编辑
import org.springframework.beans.factory.annotation.Autowired;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender; // 注入邮件发送器
/**
* 发送简单文本邮件
*/
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your-email@qq.com"); // 发件人邮箱
message.setTo(to); // 收件人邮箱
message.setSubject(subject); // 邮件主题
message.setText(content); // 邮件正文
try {
mailSender.send(message);
System.out.println("简单邮件发送成功");
} catch (Exception e) {
System.err.println("发送邮件失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 发送HTML邮件
*/
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
// true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your-email@qq.com");
helper.setTo(to);
helper.setSubject(subject);
// 设置为HTML格式
helper.setText(content, true);
mailSender.send(message);
System.out.println("HTML邮件发送成功");
} catch (MessagingException e) {
System.err.println("发送HTML邮件失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 发送带附件的邮件
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your-email@qq.com");
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);
System.out.println("带附件的邮件发送成功");
} catch (MessagingException e) {
System.err.println("发送带附件的邮件失败: " + e.getMessage());
e.printStackTrace();
}
}
}
4. 在 Controller 或其他组件中调用
最后,在你的控制器(Controller)或其他业务逻辑中,注入 MailService 并调用相应的方法。
java
编辑
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/send")
public String sendMail() {
mailService.sendSimpleMail("recipient@example.com", "主题:这是一封测试邮件", "这是邮件的正文内容!");
return "邮件已发送,请查收!";
}
@GetMapping("/sendHtml")
public String sendHtmlMail() {
String htmlContent = "<h1 style='color: blue;'>这是一封HTML邮件</h1><p>支持<strong>富文本</strong>内容。</p>";
mailService.sendHtmlMail("recipient@example.com", "主题:HTML邮件", htmlContent);
return "HTML邮件已发送!";
}
}
完成以上步骤后,启动你的 Spring Boot 应用程序,访问对应的接口即可发送邮件。