Spring AI Tool 实现 邮箱发送

目的

开发自定义Tool,实现 邮箱 的发送功能,并在调用AI 大模型中使用

技术选型

javax中包含了 mail 操作相关的依赖,但构建起来略显繁琐。这里我们使用 Hutool 包实现:

text
复制代码
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.37</version> </dependency>

邮箱选择上,我们选择国内最常见的QQ邮箱

QQ邮箱提供 SMTP/IMAP服务,PC端登陆QQ邮箱 -> 设置 -> 账号与安全 -> 安全设置 -> 开启 ‘POP3/IMAP/SMTP/Exchange/CardDAV 服务’

注:开启服务需要先绑定手机号

开通后,系统会提供一个生成好的授权码。同时,QQ邮箱提供了多种的设置方式:

image.png 不同的设置方法对应不同的服务器和端口。

开发实践

我们使用 Hutool 中的 MailAccount 实现,其最主要的参数有:host, port,from,pass:

参数名称作用
host访问的服务器地址
port服务器对应的端口号
from从哪个邮箱账号发送
pass通行证,这里需要放入刚刚生成的授权码

将所需信息放入配置文件中:

text
复制代码
mail: host: smtp.qq.com port: 465 from: ${你的邮箱账号} pass: ${你的授权码} # QQ 邮箱授权码,而非登录密码

这里使用 SMTP 设置方法。

自定义 MailSendTool 方法:

text
复制代码
public class MailSendTool { private final MailAccount account; public MailSendTool(String host, int port, String from, String pass) { account = new MailAccount(); account.setHost(host); account.setPort(port); account.setAuth(true); account.setFrom(from); account.setPass(pass); account.setSslEnable(true); // QQ 邮箱必须开启 SSL } /** * @param to 收件人邮箱 * @param subject 邮件标题 * @param content 邮件正文,可为 HTML * @param html 是否为html格式 */ @Tool(description = "Send email to a user with subject and content.") public String sendMail(@ToolParam(description = "Email address to send to.") String to, @ToolParam(description = "Email subject") String subject, @ToolParam(description = "Email content") String content, @ToolParam(description = "If the content is .html style") boolean html) { try { MailUtil.send(account, to, subject, content, html); return "邮件发送成功 -> " + to; } catch (Exception e) { return "邮件发送失败:" + e.getMessage(); } } }

Hutool包的优势体现在这里,只需一行代码即可配置并兼容。

MailSendTool 加入 项目 ToolRegistration中,采用依赖注入模式:

text
复制代码
@Configuration public class ToolRegistration { @Value("${mail.host}") String host; @Value("${mail.port}") int port; @Value("${mail.from}") String from; @Value("${mail.pass}") String pass; @Bean public ToolCallback[] allTools() { MailSendTool mailSendTool = new MailSendTool(host, port, from, pass); return ToolCallbacks.from( mailSendTool ); } }

测试功能:

text
复制代码
@SpringBootTest class MailSendToolTest { @Test void sendMail() { String host = "smtp.qq.com"; int port = 465; String from = "${你的邮箱}@qq.com"; String pass = "${你的授权码}"; MailSendTool mailSendTool = new MailSendTool(host, port, from, pass); String res = mailSendTool.sendMail("xxx@gmail.com", "第一次测试", "你好,很高兴见到你", false); System.out.println(res); } }

报错解决

当上述代码运行时,会报错:

java.lang.NoClassDefFoundError: javax/mail/Authenticator

原因是: Hutool邮件模块依赖的是旧版 javax.mail,但现在 JavaMail 已经迁移为 Jakarta Mail,但我所使用的 Hutool 版本 还没有升级,因此需要手动添加 javax.mail 依赖:

text
复制代码
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.0</version> </dependency>

扩展点

  1. 附件支持 - 将图片、PDF、生成的报告等作为附件发送
  2. 异步发送 + 限流 - 避免阻塞主线程,防止因网络波动邮件发送效率慢导致整个AI调用进程受阻
  3. 多种邮箱支持 - 目前只有针对 QQ邮箱 的实现,后续可抽象出 MailProvider接口
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP