邮件发送工具类支持附件

问题描述:动态配置邮件模板、发件人、收件人、抄送人。最开始沿用的上一个项目的工具类emailUtil发送邮件,开发时发件箱配置的同一个邮箱地址,功能OK,上测试前一天用多个发件箱进行自测,出错了。
错误信息501 mail from address must be same as authorization user
百度找到原因:发邮件时,会根据配置信息(host、port(25端口:mtp协议,465端口:smtp协议))去获取session,切换发件箱应该重新获取新的session;
查看emailUtil源码,发现获取session时用的是getDefaultInstance方法;
getDefaultInstance与getInstance的区别
getDefaultInstance: 查找缓存,若存在Properties 信息就用加载当前存在的session,若不存在,则根据当前的Properties获取seeeion;
getInstance: 直接根据当前的Properties获取seeeion;
然后百度没找到能直接使用的工具类,就自己写了个,若后期其他地方要用,再进行优化,暂时记录备忘。

import xx.xxx.xxxx.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.*;

public class SendMailUtil {

    /*
    *
     * @Author zll
     * @Description 发送邮件工具类
     * @Date 上午 10:37 2021/1/20 0020
     * @Param host:服务器 port:端口 from:发件箱地址 password:发件箱密码 subject:邮件主题 content:邮件正文 to:收件人 cc:抄送人 bbc:密送人 files:附件
     * @return
     **/
    private static Logger logger = LoggerFactory.getLogger(SendMailUtil.class);
    public static ServerResponse sendMail(String host, int port, String from, String password, String subject, String content, List<String> to, List<String> cc, List<String> bbc, List<File> files) {
//        ResponseVo responseVo = new ResponseVo();
        try {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.port", String.valueOf(port));
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            Session session = Session.getInstance(props);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setRecipients(MimeMessage.RecipientType.TO,arrayStringToArrayInternetAddress(to));
            if(null != cc && cc.size()>0){
                message.setRecipients(MimeMessage.RecipientType.CC, arrayStringToArrayInternetAddress(cc));
            }
            if(null != bbc && bbc.size()>0){
                message.setRecipients(MimeMessage.RecipientType.BCC, arrayStringToArrayInternetAddress(bbc));
            }
            MimeMultipart mime = new MimeMultipart("mixed");
            for(File file : files){
                if(null != file){
                    BodyPart mdp = new MimeBodyPart();
                    mdp.setDataHandler(new DataHandler(new FileDataSource(file)));
                    String newFileName =  MimeUtility.encodeText(file.getName(),"utf-8",null);
                    mdp.setFileName(newFileName);
                    mime.addBodyPart(mdp);
                }
            }
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(content, "text/html;charset=UTF-8");
            mime.addBodyPart(htmlPart);

            message.setContent(mime);

            Transport transport = session.getTransport();
            transport.connect(from, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e){
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }
    private static InternetAddress[] arrayStringToArrayInternetAddress(List<String> list) {

        InternetAddress[] listAddress = new InternetAddress[list.size()];

        for (int i = 0; i < list.size(); i++) {
            try {
                listAddress[i] = new InternetAddress(list.get(i));
            } catch (AddressException ex) {
                logger.error("【发送邮件失败】原因{}",ex.getMessage());
            }
        }
        return listAddress;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值