package com.yihu.jw.base.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Properties;

/**
 * Created by zdm on 2018/11/21.
 */
@Component
public class SendEmailUtils {
    private static String username;
    private  static  String smtp;
    private  static  String host;
    private  static  String port;
    private  static  String auth;
    private  static  String timeout;
    private  static  String password;



    /**
     * mimeMessage发送邮件
     * @param email 目标邮箱
     * @param content 邮件主体内容
     * @param subject 邮件标题
     * @return
     */
    public static  boolean mimeMessage(String email,String content,String subject){
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", smtp);// 连接协议
        props.setProperty("mail.smtp.host", host);// 连接协议
        props.setProperty("mail.smtp.port", port);// 连接协议
        // 指定验证为true
        props.setProperty("mail.smtp.auth", auth);
        props.setProperty("mail.smtp.timeout",timeout);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // 验证账号及密码，密码需要是第三方授权码
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(username, password);
            }
        };
        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message，它相当于是邮件内容
        MimeMessage message = new MimeMessage(session);
        try {
            //防止成为垃圾邮件，披上outlook的马甲
            message.addHeader("X-Priority", "3");

            message.addHeader("X-MSMail-Priority", "Normal");

            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");   //本文以outlook名义发送邮件，不会被当作垃圾邮件

            message.addHeader("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");

            message.addHeader("ReturnReceipt", "1");
            // 设置发送者
            String nick=javax.mail.internet.MimeUtility.encodeText("厦门i健康");
            message.setFrom(new InternetAddress(nick+" <"+username+">"));
            // 设置发送方式与接收者
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
            // 设置主题
            message.setSubject(subject);
            //创建消息主体
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //发送的内容
            messageBodyPart.setText(content);
            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            // 设置邮件消息发送的时间
            message.setSentDate(Calendar.getInstance().getTime());
            // 设置内容
            message.setContent(multipart, "text/html;charset=utf-8");
            // 3.创建 Transport用于将邮件发送
            Transport.send(message);
        }catch (Exception e){
            e.printStackTrace();
        }
            return  true;
    }

    /**
     * 邮件发送
     * @param email 目标邮箱
     * @param content 邮件主体内容
     * @param subject 邮件主题
     * @return
     */
    public static boolean  sendMessage(String email,String content,String subject){
        // 配置
        Properties prop=new Properties();
        // 设置邮件服务器主机名，这里是163
        prop.put("mail.host",host );
        // 发送邮件协议名称
        prop.put("mail.transport.protocol",smtp);
        // 是否认证
        prop.put("mail.smtp.auth", auth);

        try {
            // SSL加密
            MailSSLSocketFactory sf = null;
            sf = new MailSSLSocketFactory();
            // 设置信任所有的主机
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", true);
            prop.put("mail.smtp.ssl.socketFactory", sf);

            // 创建会话对象
            Session session = Session.getInstance(prop, new Authenticator() {
                // 认证信息，需要提供"用户账号","授权码"
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            // 是否打印出debug信息
//            session.setDebug(true);

            // 创建邮件
            Message message = new MimeMessage(session);
            // 邮件发送者
            message.setFrom(new InternetAddress(username));
            // 邮件接受者
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 邮件主题
            message.setSubject(subject);
            message.setContent(content, "text/html;charset=UTF-8");
            // Transport.send(message);
            // 邮件发送
            Transport transport = session.getTransport();
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }


    @Value("${spring.mail.username}")
    public void setUsername(String username) {
        SendEmailUtils.username = username;
    }

    @Value("${spring.mail.protocol}")
    public void setSmtp(String smtp) {
        SendEmailUtils.smtp = smtp;
    }


    @Value("${spring.mail.host}")
    public void setHost(String host) {
        SendEmailUtils.host = host;
    }

    @Value("${spring.mail.port}")
    public void setPort(String port) {
        SendEmailUtils.port = port;
    }

    @Value("${spring.mail.properties.mail.smtp.auth}")
    public void setAuth(String auth) {
        SendEmailUtils.auth = auth;
    }


    @Value("${spring.mail.timeout}")
    public void setTimeout(String timeout) {
        SendEmailUtils.timeout = timeout;
    }


    @Value("${spring.mail.password}")
    public void setPassword(String password) {
        SendEmailUtils.password = password;
    }

}
