Mail Plugin
对应模块:
io.gitee.lcgyl:lcgyl-mail-plugin
邮件发送插件,提供简单易用的邮件发送能力。
✨ 特性
- ✅ 简单 API - 一行代码发送邮件
- ✅ 多种格式 - 支持纯文本和 HTML 邮件
- ✅ 附件支持 - 支持文件附件和内嵌图片资源
- ✅ 异步发送 - 基于虚拟线程的异步发送,支持回调
- ✅ 安全连接 - 支持 SSL/TLS 加密
- ✅ Spring 集成 - 开箱即用的 Spring Boot 自动配置
- ✅ 零依赖核心 - 核心功能可脱离 Spring 独立使用
🚀 快速开始
依赖引入
gradle
implementation 'io.gitee.lcgyl:lcgyl-mail-plugin:2.2.0'配置邮箱
在 application.yml 中配置:
yaml
lcgyl:
mail:
host: smtp.qq.com # SMTP 服务器
port: 587 # 端口(587-TLS, 465-SSL)
username: your@qq.com # 邮箱账号
password: your-auth-code # 授权码(非邮箱密码)
from: your@qq.com # 发件人邮箱
from-name: LCGYL System # 发件人显示名称
starttls-enabled: true # 启用 STARTTLS发送邮件
java
@Autowired
private MailSender mailSender;
// 发送简单文本邮件
mailSender.send("recipient@example.com", "测试主题", "这是邮件内容");
// 发送 HTML 邮件
mailSender.sendHtml("recipient@example.com", "测试主题",
"<h1>Hello</h1><p>这是 HTML 邮件</p>");
// 异步发送(带回调)
mailSender.sendAsync(message,
() -> log.info("发送成功"),
error -> log.error("发送失败", error)
);📝 高级用法
发送复杂邮件
java
MailMessage message = MailMessage.builder()
.to("recipient@example.com")
.cc("cc@example.com") // 抄送
.bcc("bcc@example.com") // 密送
.subject("重要通知")
.htmlContent("<h1>标题</h1><p>内容</p>")
.attachment("report.pdf", new File("/path/to/report.pdf"))
.highPriority() // 高优先级
.build();
mailSender.send(message);带内嵌图片的 HTML 邮件
java
MailMessage message = MailMessage.builder()
.to("recipient@example.com")
.subject("带图片的邮件")
.htmlContent("<h1>Hello</h1><img src='cid:logo'/>")
.inlineResource("logo", new File("/path/to/logo.png"))
.build();
mailSender.send(message);⚙️ 配置参数
| 参数 | 说明 | 默认值 |
|---|---|---|
host | SMTP 服务器地址 | - |
port | SMTP 端口 | 587 |
username | 用户名(邮箱) | - |
password | 密码/授权码 | - |
from | 发件人邮箱 | - |
from-name | 发件人名称 | - |
ssl-enabled | 启用 SSL | false |
starttls-enabled | 启用 STARTTLS | true |
auth-enabled | 启用认证 | true |
connection-timeout | 连接超时(ms) | 5000 |
timeout | 读取超时(ms) | 10000 |
debug | 调试模式 | false |
📧 常见邮箱配置
QQ 邮箱
yaml
lcgyl:
mail:
host: smtp.qq.com
port: 587
starttls-enabled: true163 邮箱
yaml
lcgyl:
mail:
host: smtp.163.com
port: 465
ssl-enabled: true
starttls-enabled: falseGmail
yaml
lcgyl:
mail:
host: smtp.gmail.com
port: 587
starttls-enabled: true企业邮箱(腾讯)
yaml
lcgyl:
mail:
host: smtp.exmail.qq.com
port: 465
ssl-enabled: true🔧 非 Spring 环境使用
java
// 创建配置
MailProperties properties = new MailProperties();
properties.setHost("smtp.qq.com");
properties.setPort(587);
properties.setUsername("your@qq.com");
properties.setPassword("授权码");
properties.setFrom("your@qq.com");
properties.setStarttlsEnabled(true);
// 创建发送器
MailSender sender = new JavaMailSender(properties);
// 发送邮件
sender.send("recipient@example.com", "主题", "内容");
// 使用完毕后关闭
((JavaMailSender) sender).close();