平时常见的场景有通过邮件实现验证码功能,本文以qq邮箱发送邮件为例,使用hutool工具包
1、maven加入以下配置
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.1</version> <!-- 请检查最新的版本号 -->
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version> <!-- 请检查是否有更新的版本 -->
</dependency>
2、上代码
host:smtp服务器地址
port: 端口号,qq邮箱默认为 587
auth:默认true
from:发件人的邮箱地址
user: 同发件人邮箱地址就可以
pass:在qq邮箱开启smtp服务时,会产生这里的密码
MailAccount account = new MailAccount();
account.setHost("smtp.qq.com"); // SMTP 服务器地址
account.setPort(587); // 端口
account.setAuth(true); // 启用认证
account.setFrom("123@qq.com"); // 发送者邮箱
account.setUser("123@qq.com"); // 用户名
account.setPass("abcdefg"); // 授权码
account.setStarttlsEnable(true); // 启用 STARTTLS
account.setSslEnable(false); // 不启用 SSL,因为使用的是 587 端口
try {
// 解决连接 SMTP 服务失败问题
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
account.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
// 构建 HTML 格式的邮件内容 根据自己的邮件格式调整
String content = "<html><body style='font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>"
+ "<div style='background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'>"
+ "<h1 style='color: #ff0000;'>【充值失败提醒】</h1>"
+ "<p><strong>充值账号:</strong><span style='color: #333333;'>" + yxzh + "</span></p>"
+ "<p><strong>数量:</strong><span style='color: #333333;'>" + count+ "</span></p>"
+ "<p><strong>订单号:</strong><span style='color: #333333;'>" + orderNo + "</span></p>"
+ "<p><strong>失败原因:</strong><span style='color: #ff0000;'>" + msg + "</span></p>"
+ "<p><strong>时间:</strong><span style='color: #333333;'>" + DateUtil.now() + "</span></p>"
+ "</div>"
+ "</body></html>";
// 发送 HTML 格式的邮件
String result = MailUtil.send(account, toEmail, subject, content, true); // 设置为 true 发送 HTML 格式
System.out.println("发送邮件---"+result);
3、qq邮箱如何开启smtp服务
登录qq邮箱 --> 左上角顶部点击设置 --> 选择tab账户 --> 下滑看到smtp配置