package com.ruoyi.hywz.utils;

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.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class MailUtil {

    private static MailUtil mailUtil = null;

    public static MailUtil getInstance(){
        if(mailUtil==null){
            mailUtil = new MailUtil();
        }
        return mailUtil;
    }

    public void singleSendMail(String mailId,String mailpsw,String subject,String content,String targetId) throws MessagingException, IOException {
        List<String> targetIds = new ArrayList<>();
        targetIds.add(targetId);
        baseSendMail(mailId,mailpsw,subject,null,null,content,targetIds);
    }

    public void groupSendMail(String mailId,String mailpsw,String subject,String content,List<String> targetId) throws MessagingException, IOException {
        baseSendMail(mailId,mailpsw,subject,null,null,content,targetId);
    }

    public  void baseSendMail(String mailId, String mailpsw,String subject,String fileName,String filePath,String content, List<String> targetId) throws MessagingException, IOException {
        Properties props = new Properties();
        props.put("mail.smtp.host","newmail.sgcc.com.cn");
        props.put("mail.smtp.port","25");
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.starttls.enable","false");
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailId,mailpsw);
            }
        });
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailId));
        Address[] addresses = new InternetAddress[targetId.size()];
        for (int i=0;i<targetId.size();i++){
            addresses[i] = new InternetAddress(targetId.get(i));
        }
        message.setRecipients(Message.RecipientType.TO, addresses);
        message.setSubject(subject);
        if(fileName!=null){
            BodyPart filePart = new MimeBodyPart();
            filePart.setFileName(fileName);
            filePart.setDataHandler(new DataHandler(new ByteArrayDataSource(Files.readAllBytes(Paths.get(filePath)),"application/octet-stream")));
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(filePart);
            message.setContent(multipart);
        }
        message.setText(content,"utf-8","html");
        Transport.send(message);
    }
}
