package com.dji.sample.mail.util;

import com.dji.sample.mail.dao.MailBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
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;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;

@Component
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    MailProperties mailProperties;

    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailProperties.getUsername());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 发送邮件测试方法
     */
    public void sendMail(MailBean mailBean) {
        SimpleMailMessage mimeMessage =new SimpleMailMessage();
        mimeMessage.setFrom(mailProperties.getUsername());
        mimeMessage.setTo(mailBean.getToAccount());
        mimeMessage.setSubject(mailBean.getSubject());
        mimeMessage.setText(mailBean.getContent());
        mailSender.send(mimeMessage);
    }

    /**
     * 发送邮件-附件邮件
     * @param boMailBean
     */
//    public boolean sendMailAttachment(MailBean boMailBean) {
//        try {
//            MimeMessage mimeMessage =mailSender.createMimeMessage();
//            MimeMessageHelper helper =new MimeMessageHelper(mimeMessage, true);
//            helper.setFrom(mailProperties.getUsername());
//            helper.setTo(boMailBean.getToAccount());
//            helper.setSubject(boMailBean.getSubject());
//            helper.setText(boMailBean.getContent(), true);
//b            helper.addAttachment(MimeUtility.encodeWord(boMailBean.getAttachmentFileName(), "utf-8", "B"), boMailBean.getAttachmentFile());
//            mailSender.send(mimeMessage);
//            return true;
//        }catch (MessagingException | UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
}
