package cn.timer.api.utils.email;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author wuqingjun
 * @email 284718418@qq.com
 * @date 2022/4/13
 */
@Component
public class EmailUtils {

    /**
     * 发送人邮箱
     */
    private static String from;

    @Value("${spring.mail.username}")
    private void setFrom(String from) {
        EmailUtils.from = from;
    }

    /**
     * 普通发送邮件
     *
     * @param text
     * @param toMails
     * @throws MessagingException
     */
    public static int sendSimpleMail(JavaMailSender javaMailSender,String text,String subject, String... toMails) {
        if (StringUtils.isEmpty(text) || ArrayUtils.isEmpty(toMails)) {
            return 0;
        }
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(subject);
            message.setFrom(from);
            message.setBcc(from);
            message.setTo(toMails);
            message.setText(text);
            javaMailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }


    /**
     * 发送 thymeleaf 页面邮件
     *
     * @param javaMailSender
     * @param text
     * @param toMails
     * @param subject
     * @throws MessagingException
     */
    public static int sendThymeleafMail(JavaMailSender javaMailSender, String text,String subject, String... toMails) {
        if (StringUtils.isEmpty(text) || ArrayUtils.isEmpty(toMails)) {
            return 0;
        }
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject(subject);
            helper.setFrom(from);
            helper.setBcc(from);
            helper.setTo(toMails);
            helper.setText(text,true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }


}