添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
添加配置
spring:
mail:
host: smtp.qq.com
port: 465
username: your@qq.com
password: 你的16位授权码
properties:
mail:
smtp:
auth: true
ssl:
enable: true
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
// 纯文本邮件
public void sendText(String to, String subject, String text) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(from);
msg.setTo(to);
msg.setSubject(subject);
msg.setText(text);
mailSender.send(msg);
}
}
// 内嵌图片邮件
public void sendImage(String to, String subject, String htmlContent, String imagePath) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // HTML格式
// 添加内嵌图片,contentId 用于在HTML中引用
FileSystemResource image = new FileSystemResource(imagePath);
helper.addInline("imageId", image); // "imageId" 是图片的引用ID
mailSender.send(msg);
}
String html = "<html><body>" +
"<h1>带图片的邮件</h1>" +
"<img src='cid:imageId'>" + // cid: 后面跟 addInline 的 ID
"</body></html>";
// 带附件邮件
public void sendAttachment(String to, String subject, String text, String filePath) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, false); // false=纯文本
// 添加附件
FileSystemResource file = new FileSystemResource(filePath);
helper.addAttachment(file.getFilename(), file); // 使用原文件名
mailSender.send(msg);
}
// 完整功能:HTML + 内嵌图片 + 附件
public void sendFull(String to, String subject, String htmlContent,
String imagePath, String attachmentPath) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // HTML内容
// 内嵌图片
if (imagePath != null) {
FileSystemResource image = new FileSystemResource(imagePath);
helper.addInline("imageId", image);
}
// 附件
if (attachmentPath != null) {
FileSystemResource file = new FileSystemResource(attachmentPath);
helper.addAttachment(file.getFilename(), file);
}
mailSender.send(msg);
}