Springboot2.x 集成javamail发送邮件高级版

2020-11-05  本文已影响0人  骑蚂蚁上高速_jun

由于在工作中碰到一个台湾客户的邮箱,在发送邮件时,php库的swiftmail 对该邮箱支持不够好,经实验测试javamail更适合做网络底层通信,故在 原有php业务基础上加 一套javamail用来发送特殊邮箱。

  1. 添加javamail坐标到pom.xml
<dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>jakarta.mail</artifactId>
        <version>1.6.5</version>
</dependency>
  1. 配置发送邮件的线程池
@Configuration
@EnableAsync
public class AsyncThreadConfiguration {

    @Bean("smtpMailer")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);// 核心线程数(最小线程数)
        executor.setMaxPoolSize(50); // 设置最大线程
        executor.setQueueCapacity(200); // 用来缓冲执行任务的队列
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("smtpmail-"); // 设置线程名称
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
  1. 创建发送邮件的实体
package cn.http.request;

import cn.http.request.interfaces.SendMailerInterfaces;
import lombok.Data;

import javax.validation.constraints.*;
import java.util.List;
import java.util.Map;

@Data
public class SmtpRequest
{
    @NotBlank(message = "SMTP邮件服务器不能为空",groups = {SendMailerInterfaces.class})
    private String smtpHost;

    private int isSSL = 1;

    @Email(message = "发件箱格式有误",groups = {SendMailerInterfaces.class})
    @NotBlank(message ="发件箱不能为空")
    private String sendEmail ;

    @NotBlank(message = "发件密码或授权码不能为空",groups = {SendMailerInterfaces.class})
    private String password;

    // 多个收件地址使用 英文逗号隔开
    @NotBlank(message = "收件人邮箱地址不能为空",groups = {SendMailerInterfaces.class})
    private String receiveEmail;

    // 多个回复地址使用 英文逗号隔开
    private String replyEmail;

    private String cc; // 抄送 英文逗号隔开

    private String bcc; // 密送 英文逗号隔开

    @NotBlank(message = "发件主题不能为空",groups = {SendMailerInterfaces.class})
    private String subject;

    private String body; // 邮件内容

    private List<Map<String,Object>> attachs = null; // 附件

    private String messageId; // 邮件的 MessageId

    // 是否加入回执
    private int isReceipt = 0;

    // 是否紧急
    private int isPriority = 0;

    // 是否加入追踪
    private int isTrace = 0;

    // 是否异步发送
    private int isAsync = 1;

}

  1. 发送邮件的核心代码
package cn.task;

import cn.http.request.SmtpRequest;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.*;

@Slf4j
@Component
public class SmtpSendMailerTask {

    String protocol = "smtp";

    String smtpAuth = "true";

    @Async("smtpMailer") // 使用线程的Bean
    public void sendMailer(SmtpRequest smtpRequest) throws GeneralSecurityException, NoSuchProviderException {
        log.warn("接收到发送邮件 sendEmail:"+ smtpRequest.getSendEmail() +" : receiveEmail:"+smtpRequest.getReceiveEmail());
        System.out.println("发送的线程是:"+Thread.currentThread().getName());
        // 初始化属性
        Properties prop = new Properties();
        prop.setProperty("mail.host", smtpRequest.getSmtpHost()); //设置邮件服务器
        prop.setProperty("mail.transport.protocol", protocol); // 邮件发送协议
        prop.setProperty("mail.smtp.auth", smtpAuth); // 需要验证用户名密码

        // ssl
        if(smtpRequest.getIsSSL() == 1){
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
        }
        // 创建 Session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
            return new PasswordAuthentication(smtpRequest.getSendEmail(), smtpRequest.getPassword());
            }
        });
        session.setDebug(false);
        Transport ts = session.getTransport();

        try {
            ts.connect( smtpRequest.getSmtpHost(), smtpRequest.getSendEmail(), smtpRequest.getPassword()); // 尝试链接发件箱的邮件服务器
        } catch (MessagingException e) {
            log.warn("邮件发送失败 : 邮件服务器连接失败");
            return;
        }

        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);


        // 指定邮箱标题 和 内容
        try {
            // 设置发件箱
            message.setFrom(new InternetAddress(smtpRequest.getSendEmail()));

            // 设置收件人
            Address[] internetAddressTo = new InternetAddress().parse(smtpRequest.getReceiveEmail());
            message.setRecipients(Message.RecipientType.TO, internetAddressTo);

            // 设置回复人
            String replyEmail = smtpRequest.getReplyEmail();
            if(!StringUtils.isEmpty(replyEmail)){
                Address[] replyEmailAddressTo =  new InternetAddress().parse(replyEmail); // 设置回复地址
                message.setReplyTo(replyEmailAddressTo);
            }

            // 设置抄送
            String cc = smtpRequest.getCc();
            if(!StringUtils.isEmpty(cc)){
                message.setRecipients(Message.RecipientType.CC,cc);
            }
            // 设置密送
            String bcc = smtpRequest.getBcc();
            if(!StringUtils.isEmpty(bcc)){
                message.setRecipients(Message.RecipientType.BCC,bcc);
            }
            // 设置紧急邮件
            if(smtpRequest.getIsPriority() == 1){
                message.setHeader("X-Priority", "1");
            }
            // 设置回执
            if(smtpRequest.getIsReceipt() == 1){
                message.setHeader("Disposition-Notification-To", smtpRequest.getSendEmail());
            }


            String messageId = smtpRequest.getMessageId();
            // 设置 Message-Id
            if(!StringUtils.isEmpty(messageId)){
                if(messageId.startsWith("<") && messageId.endsWith(">") && messageId.indexOf("@")!=-1){
                    message.setHeader("Message-ID",messageId);
                }
            }
            message.setHeader("ZMKM","BUS");
            message.setHeader("Ident","Wml Bus[2]");
            message.setHeader("Content-Description","DongGuan TradeWolf Business");

            message.setSentDate(new Date());
            message.setSubject(smtpRequest.getSubject());
            // 设置正文

            message.setContent(createPart(smtpRequest));
           ts.sendMessage(message, message.getAllRecipients());
            ts.close(); /**/
            log.warn("邮件发送成功");
        } catch (MessagingException e) {
            log.warn("邮件发送失败,"+e.getMessage());

        }
    }

    /**
     * 创建邮件主体 body 和 附件
     * @param smtpRequest
     * @return
     */
    private MimeMultipart createPart(SmtpRequest smtpRequest) throws MessagingException {
        // 1.设置正文,正文图片,附件三者的混合节点
        MimeMultipart multipart = new MimeMultipart();
        String body = smtpRequest.getBody();
        Document documentRoot = Jsoup.parse(body);
        Elements imgElements = documentRoot.getElementsByTag("img");
        int imgCount = imgElements.size();

        // 2. 设置正文和正文图片的混合节点
        MimeMultipart htmlImagePart = new MimeMultipart();

        for (int i=0;i<imgCount;++i){
            // 存在跟踪那么最后一张图片就必须原样发送;
            if(smtpRequest.getIsTrace() > 0 && i == imgCount-1){
                System.out.println("存在跟踪并且是最后一张图片,那么最后一张图片不需要上传到邮件服务器");
                continue;
            }
            // 3. 设置图片节点
            MimeBodyPart imagePart = new MimeBodyPart();
            Element imgElement = imgElements.get(i);
            String imgSrcStr = imgElement.attr("src");//获取到src的值
            if(StringUtils.isEmpty(imgSrcStr)) continue;
            URL url  = null;
            try{
                url = new URL(imgSrcStr);
                DataHandler dh = new DataHandler(url);
                imagePart.setDataHandler(dh);
                imagePart.setContentID("m"+i);
                imgElement.attr("src", "cid:m"+i); // 替换图片src节点
            }catch(MalformedURLException e){
                continue; //
            }
            htmlImagePart.addBodyPart(imagePart); // 将图片节点绑定到混合节点
        }
        String newHtml = documentRoot.body().toString();//处理后的HTML

        // 2.设置正文节点
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(newHtml,"text/html;charset=utf-8");

        // 3.设置图片与正文关联节点
        htmlImagePart.addBodyPart(htmlPart);
        htmlImagePart.setSubType("related");    // 设置正文与图片的关系

        BodyPart html_image = new MimeBodyPart();
        html_image.setContent(htmlImagePart);
        multipart.addBodyPart(html_image);

        // 设置附件
        // [{"name":"","url":""},.......] 附件的格式
        List<Map<String,Object>> attachs = smtpRequest.getAttachs();
        if(attachs!=null){
            int attachCount = attachs.size();
            if(attachCount>0) {
                for (int i = 0; i < attachCount; ++i) {
                    Map<String, Object> map = attachs.get(i);
                    String name = (String) map.get("name"); // 文件名称
                    String attachPath = (String) map.get("url"); // 文件路径
                    URL aurl = null;
                    try {
                        aurl = new URL(attachPath);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                        continue; // 不存在的附件
                    }
                    DataHandler dataHandler = new DataHandler(aurl);
                    MimeBodyPart attachPart = new MimeBodyPart();
                    attachPart.setDataHandler(dataHandler);
                    attachPart.setFileName(name);
                    multipart.addBodyPart(attachPart);
                }
            }
        }


        return multipart;
    }
}

上一篇下一篇

猜你喜欢

热点阅读