package com.qryord.common.utils;

import com.qryord.common.constant.Constants;
import com.qryord.framework.config.MailConfig;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

@Configuration
@EnableAutoConfiguration
public class MailUtil {

    private String smtpServer;
	private String smtpPort;
	private String accout;
	private String pwd;

    public MailUtil() {
    }

    public MailUtil(MailConfig mailConfig) {
    	smtpServer = mailConfig.getSmtpServer();
    	smtpPort = mailConfig.getSmtpPort();
    	accout = mailConfig.getAccout();
    	pwd = mailConfig.getPwd();
    }

    public void sendEmail(String recipient, String nickName, String mailContent) throws Exception {
        // 创建邮件配置
        Properties props = new Properties();
        // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.transport.protocol", "smtp");
        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.host", smtpServer);
        props.setProperty("mail.smtp.port", smtpPort); 
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
        props.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl

        // 根据邮件配置创建会话，注意session别导错包
        Session session = Session.getDefaultInstance(props);
        // 开启debug模式，可以看到更多详细的输入日志
        session.setDebug(true);
        //创建邮件
        MimeMessage message = createEmail(session, recipient, nickName, mailContent);
        //获取传输通道
        Transport transport = session.getTransport();
        transport.connect(smtpServer, accout, pwd);

        //连接，并发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }


    public MimeMessage createEmail(Session session, String recipient, String nickName, String mailContent) throws Exception {
        // 根据会话创建邮件
        MimeMessage msg = new MimeMessage(session);
        // address邮件地址, personal邮件昵称, charset编码方式
        InternetAddress fromAddress = new InternetAddress(accout, Constants.MAIL_SENDER, Constants.MAIL_CHARSET);
        // 设置发送邮件方
        msg.setFrom(fromAddress);

        InternetAddress[] receiveAddress =null;
        String[] toAddrs = recipient.split(",");
        receiveAddress = new InternetAddress[toAddrs.length];

        int idx = 0;

        for (String toAddress : toAddrs) {
            InternetAddress toIntAddr = new InternetAddress(toAddress, nickName, Constants.MAIL_CHARSET);
            receiveAddress[idx] = toIntAddr;
            idx = idx + 1;
        }

        // 设置邮件接收方
        msg.setRecipients(RecipientType.TO, receiveAddress);
        // 设置邮件标题
        msg.setSubject(Constants.MAIL_TITLE, "utf-8");

        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        String htmlContent = mailContent;
        htmlPart.setContent(htmlContent, "text/html;charset=UTF-8");

        multipart.addBodyPart(htmlPart);
        msg.setContent(multipart);

        // 设置显示的发件时间
        msg.setSentDate(new Date());
        // 保存设置
        msg.saveChanges();
        return msg;
    }
}