异步群发邮件含明发暗发

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class EmailUtil {
    private static Logger logger = LoggerFactory.getLogger(EmailUtil.class);
    private static Properties properties;
    static {
        InputStream in;
        try {
            properties = new Properties();
            in = EmailUtil.class.getResourceAsStream("/application.properties");
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String dir = "D:/rpt/number";
        File dirFile = new File(dir);
        if (!dirFile.exists())
            dirFile.mkdirs();
        String file = dir + "/test.txt";
        sendEmail(file, "****", "2020期");
    }


    //异步发送邮件
    public static boolean sendEmail(String filename, String subject, String msg) {
        try {
            new Thread(new Runnable() {
                public void run() {
                    sendEmailz(filename, subject, msg);
                }
            }).start();
        } catch (Exception e) {
            logger.info("异步发送邮件失败!", e);
            return false;
        }
        return true;
    }

	//参数: 文件路径   邮件主题  邮件内容
	//邮箱发件者以163邮箱为模板 需要开通SMTP协议
    public static boolean sendEmailz(String filename, String subject, String msg) {
        try {
        	//动态获取配置文件中的信息
            Properties prop = EmailUtil.getConfig("application-" + EmailUtil.getProp("spring.profiles.active") + ".properties");
            String sender = EmailUtil.getPropValue(prop, "sender");
            String cc = EmailUtil.getPropValue(prop, "cc");
            String bcc = EmailUtil.getPropValue(prop, "bcc");
            String password = EmailUtil.getPropValue(prop, "password");
            boolean s;
            //待发送文件
            File file2 = new File(filename);
            if (!file2.exists()) {
                logger.info("要发送文件不存在!");
                return true;
            }
            String[] c = cc.split(",");
            List listCC = Arrays.asList(c);

            String[] b = bcc.split(",");
            List listBCC = Arrays.asList(b);

            // 指定发送邮件的主机为 smtp.qq.com
            String host = "smtp.163.com"; // 邮件服务器

            // 获取系统属性
            Properties properties = System.getProperties();

            // 设置邮件服务器
            properties.setProperty("mail.smtp.host", host);

            properties.put("mail.smtp.auth", "true");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            // 获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                    return new PasswordAuthentication(sender, password); // 发件人邮件用户名、密码
                }
            });

            //明发
            if (!cc.isEmpty()) {
                s = sendMailC(listCC, subject, msg, filename, sender, session);
                if (s == false) {
                    logger.error("明发邮件失败,检查邮件格式是否正确!");
                    return false;
                }
            } else {
                logger.info("邮件发送未设置收件人(明发)!");
            }

            //密发
            if (!bcc.isEmpty()) {
                s = sendMailB(listBCC, subject, msg, filename, sender, session);
                if (s == false)
                    logger.error("密发邮件失败,检查邮件格式是否正确!");
            } else {
                logger.info("邮件发送未设置收件人(密发)!");
            }
        } catch (Exception e) {
            logger.info("检查邮件发送过程错误!", e);
        }
        return true;

    }

    /**
     * 发送带附件的邮件
     *
     * @param receive  收件人   明发
     * @param subject  邮件主题
     * @param msg      邮件内容
     * @param filename 附件地址
     * @return
     * @throws GeneralSecurityException
     */
    private static boolean sendMailC(List<String> receive, String subject, String msg, String filename, String sender, Session session) throws Exception {
        // 创建默认的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);
        Address[] internetAddressTo = new InternetAddress[receive.size()];
        for (int i = 0; i < internetAddressTo.length; i++) {
            internetAddressTo[i] = new InternetAddress(receive.get(i));
        }
        message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
        send(message, subject, msg, filename, sender);
        return true;
    }

    /**
     * 发送带附件的邮件
     *
     * @param receive  收件人   密发
     * @param subject  邮件主题
     * @param msg      邮件内容
     * @param filename 附件地址
     * @return
     * @throws GeneralSecurityException
     */
    private static boolean sendMailB(List<String> receive, String subject, String msg, String filename, String sender, Session session) throws Exception {
        // 创建默认的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);
        Address[] internetAddressTo = new InternetAddress[receive.size()];
        for (int i = 0; i < internetAddressTo.length; i++) {
            internetAddressTo[i] = new InternetAddress(receive.get(i));
            message.setRecipients(MimeMessage.RecipientType.BCC, receive.get(i));// 密发
            send(message, subject, msg, filename, sender);
        }
        return true;
    }

    //发送邮件准备设置工作
    public static boolean send(MimeMessage message, String subject, String msg, String filename, String sender) {
        try {
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(sender));

            // Set Subject: 主题文字
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(msg);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分
            messageBodyPart = new MimeBodyPart();
            // 设置要发送附件的文件路径
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));

            // messageBodyPart.setFileName(filename);
            // 处理附件名称中文(附带文件路径)乱码问题
            String fileN = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
            messageBodyPart.setFileName(MimeUtility.encodeText(fileN));
            multipart.addBodyPart(messageBodyPart);

            // 发送完整消息
            message.setContent(multipart);

            // 发送消息
            Transport.send(message);
        } catch (Exception e) {
            logger.info("邮件准备发送失败", e);
            return false;
        }
        return true;
    }


    public static String getProp(String key) {
        return properties.getProperty(key);
    }

    public static Properties getConfig(String name) {
        Properties props = null;
        try {
            props = new Properties();
            InputStream in = EmailUtil.class.getClassLoader().getResourceAsStream(name);
            BufferedReader bf = new BufferedReader(new InputStreamReader(in));
            props.load(bf);
            in.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return props;
    }

    public static String getPropValue(Properties prop, String key) {
        if (key == null || "".equals(key.trim())) {
            return null;
        }
        String value = prop.getProperty(key);
        if (value == null) {
            return null;
        }
        value = value.trim();
        //判断是否是环境变量配置属性,例如 server.env=${serverEnv:local}
        if (value.startsWith("${") && value.endsWith("}") && value.contains(":")) {
            int indexOfColon = value.indexOf(":");
            String envName = value.substring(2, indexOfColon);
            //获取系统环境变量 envName 的内容,如果没有找到,则返回defaultValue
            String envValue = System.getenv(envName);
            if (envValue == null) {
                //配置的默认值
                return value.substring(indexOfColon + 1, value.length() - 1);
            }
            return envValue;
        }
        return value;
    }
}
//pom.xml中添加以下依赖
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.6</version>
        </dependency>

你可能感兴趣的:(笔记)