package com.xxl.job.executor.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.List;
import java.util.Properties;

public class SendMailUtil {
    private static String protocol = "smtp";
    private static String host = "smtp.exmail.qq.com";
    private static Integer port = 465;
    private static String fromEmil = "notice@c-top.com.cn";
    private static String connectUser = "notice@c-top.com.cn";
    private static String connectPassWord = "Hcst@2019";


    public static void sendMail(List<String> mails, String subject, String text) throws Exception {
        if (Check.isNull(mails)) {
            throw new Exception("请输入邮箱");
        }

        Properties properties = new Properties();
        properties.put("mail.transport.protocol", protocol);// 连接协议
        properties.put("mail.smtp.host", host);// 主机名
        properties.put("mail.smtp.port", port);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "false");// 设置是否显示debug信息 true 会在控制台显示相关信息
        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(fromEmil));
        // 设置收件人邮箱地址

        InternetAddress[] internetAddresses = new InternetAddress[mails.size()];
        for (int i = 0; i < mails.size(); i++) {
            InternetAddress addr = new InternetAddress(mails.get(i));
            internetAddresses[i] = addr;
        }
        message.setRecipients(Message.RecipientType.TO, internetAddresses);
        // 设置邮件标题
        message.setSubject(subject);
        // 设置邮件内容
        // message.setText(text);

        BodyPart html = new MimeBodyPart();
        Multipart mainPart = new MimeMultipart();
        // 设置HTML内容
        html.setContent(text, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        message.setContent(mainPart);


        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(connectUser, connectPassWord);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }


}
