package cn.reghao.tnb.message.app.service.notifier.email;

import cn.reghao.tnb.message.app.model.po.EmailAccount;
import cn.reghao.tnb.message.app.service.EmailAccountService;
import cn.reghao.tnb.message.app.service.notifier.Notify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * 邮件通知
 *
 * @author reghao
 * @date 2021-02-25 19:23:16
 */
@Slf4j
@Service
public class EmailNotify implements Notify<EmailMsg> {
    private final EmailAccountService emailAccountService;

    public EmailNotify(EmailAccountService emailAccountService) {
        this.emailAccountService = emailAccountService;
    }

    @Override
    public void send(String receiver, EmailMsg msg) throws Exception {
        EmailAccount emailAccount = emailAccountService.getEmailSender();
        if (emailAccount == null) {
            throw new Exception("没有可用于发送通知的邮箱配置");
        }

        String smtp = emailAccount.getSmtp();
        String myEmail = emailAccount.getUsername();
        String password = emailAccount.getPassword();
        String personal = emailAccount.getPersonal();

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", smtp);
        props.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(props);

        InternetAddress from = new InternetAddress(myEmail, personal, "UTF-8");
        InternetAddress[] dest = getDestinations(receiver);
        MimeMessage message = getMessage(session, from, dest, msg);

        Transport transport = session.getTransport();
        transport.connect(myEmail, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    private InternetAddress[] getDestinations(String receiver) throws UnsupportedEncodingException {
        String[] strs = receiver.split(",");
        int len = strs.length;
        InternetAddress[] addresses = new InternetAddress[len];
        for (int i = 0; i < len; i++) {
            addresses[i] = new InternetAddress(strs[i], "", "UTF-8");
        }
        return addresses;
    }

    private MimeMessage getMessage(Session session, Address from, InternetAddress[] dest, EmailMsg msg)
            throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(MimeMessage.RecipientType.TO, dest);
        message.setSubject(msg.getSubject(), "UTF-8");
        message.setContent(msg.getContent(), "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        return message;
    }
}
