package cn.datax.service.email.utils;

import cn.datax.service.email.api.entity.EmailEntity;
import cn.hutool.core.collection.CollUtil;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

public class EmailUtil {

    private InternetAddress from;
    private JavaMailSender mailSender;

    public EmailUtil(InternetAddress from, JavaMailSender mailSender) {
        this.from = from;
        this.mailSender = mailSender;
    }

    public void sendEmail(EmailEntity mailEntity) throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setSubject(mailEntity.getSubject());
        helper.setText(mailEntity.getText(),true);
        List<String> tos = mailEntity.getTos();
        helper.setTo((String[])tos.toArray(new String[tos.size()]));
        List<String> ccs = mailEntity.getCcs();
        if(CollUtil.isNotEmpty(ccs)){
            helper.setCc((String[])ccs.toArray(new String[ccs.size()]));
        }
        List<String> bccs = mailEntity.getBccs();
        if(CollUtil.isNotEmpty(bccs)){
            helper.setBcc((String[])bccs.toArray(new String[bccs.size()]));
        }
        List<File> files = mailEntity.getFiles();
        if(CollUtil.isNotEmpty(files)){
            for (int i = 0; i < files.size(); i++) {
                File file = files.get(i);
                helper.addAttachment(file.getName(), file);
            }
        }
        mailSender.send(mimeMessage);
    }

}
