SendMailUtil.java 13.1 KB
package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

public class SendMailUtil {

    private static Logger logger = LoggerFactory.getLogger(SendMailUtil.class);


    private static String account = "lhdna-service@lhcis.com";    //登录用户名
    private static String pass = "lhdNa2016";        //登录密码
    private static String host = "smtp.exmail.qq.com";        //服务器地址(邮件服务器)
    private static String port = "465";        //端口
    private static String protocol = "smtp"; //协议
    private static String from = "联合征信"; //发件人名称
    public static final String subject = "深度版报告邮件提醒"; // 邮件标题

    static class MyAuthenricator extends Authenticator {
        String u = null;
        String p = null;

        public MyAuthenricator(String u, String p) {
            this.u = u;
            this.p = p;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(u, p);
        }
    }



    public static void send(String title,String content,String to,String cc) {
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", protocol);
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //使用SSL,企业邮箱必需!
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass));
//        session.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(account, from));        //可以设置发件人的别名
            //mimeMessage.setFrom(new InternetAddress(account));    //如果不需要就省略
            //收件人
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if(StringUtils.isNotEmpty(cc)){
                InternetAddress[] sendCc = InternetAddress.parse(cc);
                mimeMessage.setRecipients(MimeMessage.RecipientType.CC, sendCc);
            }
            //主题
            mimeMessage.setSubject(title);
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();
            //HTML正文
            body.setContent(content, "text/html; charset=UTF-8");
            mp.addBodyPart(body);

//            //添加图片&附件
//            body = new MimeBodyPart();
//            body.attachFile(fileStr);
//            mp.addBodyPart(body);

            //设置邮件内容
            mimeMessage.setContent(mp);
            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            String msg = e.getMessage();
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param title 邮件标题
     * @param content 邮件内容
     * @param to 发件人(多个发件人的地址用逗号隔开)
     * @param cc 抄送人
     */
    public static void sends(String title,String content,String to,String cc) {
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", protocol);
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //使用SSL,企业邮箱必需!
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(prop, new MyAuthenricator(account, pass));
//        session.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(account, from));        //可以设置发件人的别名
            //mimeMessage.setFrom(new InternetAddress(account));    //如果不需要就省略

            //收件人
            //设置收件人地址,以逗号隔开
            InternetAddress[] sendTo = InternetAddress.parse(to);
            mimeMessage.setRecipients(MimeMessage.RecipientType.TO, sendTo);

            if(StringUtils.isNotEmpty(cc)){
                InternetAddress[] sendCc = InternetAddress.parse(cc);
                mimeMessage.setRecipients(MimeMessage.RecipientType.CC, sendCc);
//                mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
            //主题
            mimeMessage.setSubject(title);
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();
            //HTML正文
            body.setContent(content, "text/html; charset=UTF-8");
            mp.addBodyPart(body);

//            //添加图片&附件
//            body = new MimeBodyPart();
//            body.attachFile(fileStr);
//            mp.addBodyPart(body);

            //设置邮件内容
            mimeMessage.setContent(mp);
            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            String msg = e.getMessage();
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送 附件邮件 ,多个发送人,用逗号隔开
     * @param title
     * @param content
     * @param attachmentUrlArr
     * @param to
     * @param cc
     */




    public static void sends(String title, String content, JSONArray attachmentUrlArr, String to, String cc) {
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", protocol);
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //使用SSL,企业邮箱必需!
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(prop, new MyAuthenricator(account, pass));
//        session.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(account, from));        //可以设置发件人的别名
            //mimeMessage.setFrom(new InternetAddress(account));    //如果不需要就省略

            //收件人
            //设置收件人地址,以逗号隔开
            InternetAddress[] sendTo = InternetAddress.parse(to);
            mimeMessage.setRecipients(MimeMessage.RecipientType.TO, sendTo);

            if(StringUtils.isNotEmpty(cc)){
                InternetAddress[] sendCc = InternetAddress.parse(cc);
                mimeMessage.setRecipients(MimeMessage.RecipientType.CC, sendCc);
//                mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
            //主题
            mimeMessage.setSubject(title);
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();
            //HTML正文
            body.setContent(content, "text/html; charset=UTF-8");
            mp.addBodyPart(body);
            logger.info("正在发送邮件======");
            //设置 邮件附件
            for (int i = 0; i < attachmentUrlArr.size(); i++){
                MimeBodyPart bodyPart = new MimeBodyPart();
                JSONObject obj = (JSONObject)attachmentUrlArr.get(i);
                byte[] bytes = downloadFileFromUrl(obj.getString("fileAttachments"));
                if (bytes != null){
                    ByteArrayDataSource source = new ByteArrayDataSource(bytes, "application/octet-stream");
                    bodyPart.setDataHandler(new DataHandler(source));
                    String fileName = obj.getString("fileName") + "." + obj.getString("fileExtension").toLowerCase();
                    bodyPart.setFileName(fileName);
                    logger.info("正在添加邮件附件,邮件附件名称为:" + fileName);
                    mp.addBodyPart(bodyPart);
                }
            }

            //设置邮件内容
            mimeMessage.setContent(mp);
            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
            logger.info("邮件发送完成");
        } catch (MessagingException e) {
            e.printStackTrace();
            String msg = e.getMessage();
            System.out.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据链接下载附件 并转成byte
     * @param urlString
     * @return
     * @throws IOException
     */
    private static byte[] downloadFileFromUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        try (InputStream inputStream = url.openStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }
    }

    public static void main(String[] args) {
        JSONArray array = new JSONArray();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("url","http://filestorage.lhdna.com/creditManager/1910227386859122688.docx");
//        jsonObject.put("name","aa.docx");
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("url","http://filestorage.lhdna.com/creditManager/1910583672389890048.pdf");
//        jsonObject1.put("name","bbb.pdf");
//        array.add(jsonObject);
//        array.add(jsonObject1);
        String context = "<p>报告生成失败提醒:</p>" +
                "企业名称:" + "XXXXXXX" + "</br></br>" +
                "报错信息:" ;
//            SendMailUtil.send("##报告生成失败提醒:" + "XXXXXXX" + "##", context, "liyang_bjzx@lhcis.com", "liyang_bjzx@lhcis.com,nan@lhcis.com");
        SendMailUtil.sends("##报告生成失败提醒:" + "XXXXXXX" + "##", context,array ,"18511354353@163.com", "liyang_bjzx@lhcis.com,nan@lhcis.com");
    }






}