Hutool发送邮件


1 依赖

在这里插入图片描述

	 	<!--我使用的SpringBoot版本是2.2.5.RELEASE-->
   		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.4</version>
        </dependency>
         <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

2 配置

放在classpath下,我的是springBoot,所以直接放在resources下即可
在这里插入图片描述

2.1、内容如下:

# 邮件服务器的SMTP地址
host = smtp.163.com
# 邮件服务器的SMTP的端口
port = 25
# 发件人(必须正确,否则发送失败)
from = xxx@163.com<xxx@163.com>
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
user =xxx@163.com
# 密码
pass = xxx
# 使用STARTTLS安全链接
startttlsEnable = true

3 发送

/**
 * @Author: oldlu
 * @Description:
 **/
public class MailUtilsTest {
    public static void main(String[] args) {
        String text = MailUtil.send("test@163.com", "title.test", "mail.send.test", false, null);
        System.out.println(text);
    }
}

4 总结

使用hutool的发送邮件还是很简单的,它都封装好了,我上面只是发送个文本,当然发送文件,多人发送、抄送、密文都支持,发送速度还可以的。

5 线上遇到的问题

遇到错误:

cn.hutool.extra.mail.MailException: MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 25

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Copy to clipboardErrorCopied

这个错误可能是需要SSL验证造成的也有可能是线上服务器因为阿里云屏蔽了非SSL链接的25发送邮件端口,我们可以手动跳过这个验证:

MailAccount mailAccount = new MailAccount();
mailAccount.setAuth(true);
mailAccount.setSslEnable(true);
...
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

Mail mail = Mail.create(mailAccount)
    .setTos("xx@xx.com")
    .setTitle("邮箱验证")
    .setContent("您的验证码是:<h3>2333</h3>")
    .setHtml(true)
    .send();

或者更改短信发送端口为:465

6 实例代码:

 if (StringUtils.isBlank(filePath) && StringUtils.isBlank(fileId)) {
                                MailAccount mailAccount = new MailAccount();
                                mailAccountConfig(mailAccount);
                                sendEmail(email, subject, content, mailAccount, false);
                            }
    private void mailAccountConfig(MailAccount mailAccount) throws GeneralSecurityException {
        mailAccount.setAuth(true);
        mailAccount.setSslEnable(true);
        mailAccount.setHost("smtp.163.com");
        mailAccount.setPort(465);
        mailAccount.setFrom("sdfayuan@163.com");
        mailAccount.setUser("sdfayuan");
        mailAccount.setPass("*******");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
    }
posted @ 2021-07-08 21:57  赵广陆  阅读(958)  评论(1编辑  收藏  举报