package cn.datax.service.email.service.impl;

import cn.datax.service.email.api.entity.EmailEntity;
import cn.datax.service.email.service.EmailService;
import cn.datax.service.email.utils.EmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.from}")
    private String fromNick;

    @Value("${spring.mail.username}")
    private String fromAddress;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendEmail(EmailEntity emailEntity) {
        log.info("实体类 {}", emailEntity);
        InternetAddress from = null;
        String alias = null;
        try {
            alias = MimeUtility.encodeText(fromNick);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            from = new InternetAddress(alias + " <" + fromAddress + ">");
        } catch (AddressException e) {
            e.printStackTrace();
        }
        EmailUtil emailUtil = new EmailUtil(from, mailSender);
        try {
            emailUtil.sendEmail(emailEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
