SpringBoot发送邮件
使用SpringBoot发送四种不同类型的邮件
- 发送简单文本文件
- 发送HTML渲染的界面
- 发送带附件的邮件
- 发送带图片的邮件
获取邮箱的远程登录
点击设置--->账号-->开启服务
点击服务管理
生成授权码。记住授权码,授权码只会出现一次,可以多次获取。
搭建SpringBoot工程
- 添加maven依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.13</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
- 添加发送邮件的配置文件
# 发送QQ邮箱的 代收发服务器地址。
spring.mail.host=smtp.qq.com
# qq邮箱
spring.mail.username=12345678@qq.com
# 生成的16位授权码
spring.mail.password=abcdefgrdvntrhhce
# 邮件发送的编码格式
spring.mail.default-encoding=UTF-8
- 服务接口类
package com.email.service;
public interface MailService {
/**
* 发送普通文本邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
void sendSimpleMail(String to, String subject, String content);
/**
* 发送HTML邮件
* @param to 收件人
* @param subject 主题
* @param content 内容(可以包含<html>等标签)
*/
void sendHtmlMail(String to, String subject, String content);
/**
* 发送带附件的邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param filePath 附件路径
*/
void sendAttachmentMail(String to, String subject, String content, String filePath);
/**
* 发送带图片的邮件
* @param to 收件人
* @param subject 主题
* @param content 文本
* @param rscPath 图片路径
* @param rscId 图片ID,用于在<img>标签中使用,从而显示图片
*/
void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
}
- 接口实现类
package com.email.service.Impl;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import com.email.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
@Service
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);//收信人
message.setSubject(subject);//主题
message.setText(content);//内容
message.setFrom(from);//发信人
mailSender.send(message);
}
@Override
public void sendHtmlMail(String to, String subject, String content) {
logger.info("发送HTML邮件开始:{},{},{}", to, subject, content);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);//true代表支持html
mailSender.send(message);
logger.info("发送HTML邮件成功");
} catch (MessagingException e) {
logger.error("发送HTML邮件失败:", e);
}
}
@Override
public void sendAttachmentMail(String to, String subject, String content, String filePath) {
logger.info("发送带附件邮件开始:{},{},{},{}", to, subject, content, filePath);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
mailSender.send(message);
logger.info("发送带附件邮件成功");
} catch (MessagingException e) {
logger.error("发送带附件邮件失败", e);
}
}
@Override
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);//重复使用添加多个图片
mailSender.send(message);
logger.info("发送带图片邮件成功");
} catch (MessagingException e) {
logger.error("发送带图片邮件失败", e);
}
}
}
- SpringBoot启动类
@SpringBootApplication
public class EmailApplication implements ApplicationRunner {
@Autowired
private MailService mailService;
private String TO = "1233444@gmail.com";
private String SUBJECT = "测试SpringBoot发送邮件之发送带图片的邮件";
private String CONTENT = "接收了邮件中的附件";
private String HTML = "<h1>测试邮件发送html</h1>";
private String HTML1 = "<img src='C:/Users/abc/Pictures/1694668957060.jpg'>测试邮件发送html</img>";
private String filePath="C:/Users/abc/Pictures/1694668957060.jpg";
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
@Override
public void run(ApplicationArguments args){
System.out.println("----------------------SpringBoot启动----------------------");
// 测试邮件发送简单文本
mailService.sendSimpleMail(TO, SUBJECT, CONTENT);
// 测试邮件发送HTML
mailService.sendHtmlMail(TO,SUBJECT,HTML);
// 测试邮件发送文件
mailService.sendAttachmentMail(TO,SUBJECT,CONTENT,filePath);
// 测试发带图片的邮件
mailService.sendInlineResourceMail(TO,SUBJECT,HTML1,filePath,"1234");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构