package com.jsh.erp.util;

import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

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

public class EmailTask implements Runnable {

    private final JavaMailSender mailSender;
    private final MailProperties mailProperties;
    private final String to;
    private final String subject;
    private final String text;

    public EmailTask(JavaMailSender mailSender,MailProperties mailProperties, String to, String subject, String text) {
        this.mailProperties = mailProperties;
        this.mailSender = mailSender;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }

    @Override
    public void run() {
        try {
            System.setProperty("mail.mime.splitlongparameters", "false");
            // 创建邮件消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
            // 发送邮件
            mailSender.send(message);
            System.out.println("邮件发送成功：" + to);
        } catch (MessagingException e) {
            System.err.println("邮件发送失败：" + to + "，错误信息：" + e.getMessage());
        }
    }
}
