Java根据Hutool发送邮件(个人、企业)

Hutool依赖

 <dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
 </dependency>

将邮件发送封装一下(按需实现)

/**
 * 发送多个邮件
 * @param emails 邮件地址
 * @param title 标题
 * @param body 内容
 * @param fileUrl 附件
 * @throws Exception
 */
@Async("taskExecutor")
public void send(List<String> emails , String title , String body , String fileUrl) {
    if (CollUtil.isNotEmpty(emails)) {
        if (StrUtil.isNotEmpty(fileUrl)) {
            File file = getFile(fileUrl);
            MailUtil.sendHtml(emails, title , body , file);
        } else {
            MailUtil.sendHtml(emails, title , body);
        }
    }
}

/**
 * 将文件地址以流的形式解析出来
 * url 文件地址(远程地址)
 * /
public static File getFile(String url) {
    String fileType = url.substring(url.lastIndexOf(".")).toLowerCase();
    File file = FileUtil.createTempFile("Venture",fileType,true);
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        URL fileUrl = new URL(url);
        inputStream = fileUrl.openStream();
        outputStream = FileUtil.getOutputStream(file);
        int bytesRead = 0;
        int size = 8192;
        byte[] buffer = new byte[size];
        while ((bytesRead = inputStream.read(buffer, 0, size)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServiceException(e.getMessage());
    } finally {
        try {
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
    }
    return file;
}

添加配置mail.setting(放在静态资源resources下)

企业所需配置
host = 邮件类型
port = 端口
from= 发送人
user = 发送人名称
pass= SMTP服务码密码
startttlsEnable = true
sslEnable = true

个人所需配置项
from= 发送人
pass= SMTP服务码密码

遇到的坑

  • AuthenticationFailedException: 535 Error: authentication failed, system busy 。 可能密码不正确,该密码不为登录密码,为设置中开启SMTP服务所得密码。
  • 163邮箱中附件显示为.bin文件,QQ邮箱则正常显示。原因附件名称过长(有高手可以重写,仅存在getFile方法,有大神可以加以改造让其正确,Venture改"资源附件"则复现原因)。
  • 邮箱判定为垃圾内容。被驳回。
    错误
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值