package com.chushang.common.mail.utils;

import com.chushang.common.core.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
public class MailUtils {

    private static final JavaMailSender javaMailSender = SpringUtils.getBean(JavaMailSender.class);

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

    public static void send(String from, String[] to, String subject, String content, Boolean isHtml) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setText(content, isHtml);
        helper.setSubject(subject);
        javaMailSender.send(mimeMessage);
    }

    public static void sendText(String[] to, String subject, String content) throws MessagingException {
        send(from, to, subject, content, false);
    }

    public static void sendHtml(String[] to, String subject, String content) throws MessagingException {
        send(from, to, subject, content, true);
    }

}