EmailUtil 邮件发送工具类

在工作中,经常遇到警告、异常等数据,需要以某些方式告知维护人员。比较通常的方式是邮件,也有用企业微信的。通常邮件使用apache的emali工具类。

添加maven依赖:



    org.apache.commons
    commons-email
    1.5

application.yml添加配置

srping:
  email:
    host: **.com          #邮件服务器
    from: **@**.com        #邮件发送账户
    username: **@**.com    #发送账户的用户名
    password: **           #发送账户的密码
    defaultEncoding: UTF-8
    to: **@**.com          #接收账户
    title: **              #邮箱标题

邮箱配置类

@Configuration
@ConfigurationProperties(prefix = "spring.email")
public class EmailConfig {

    private String host;

    private String from;

    private String username;

    private String password;

    private String defaultEncoding;

    private String to;

    private String title;
}

发送邮件工具类

public class EmailUtil {

    private EmailConfig emailConfig;


    private Logger logger = LoggerFactory.getLogger(getClass());


    public EmailUtil(EmailConfig emailConfig) {
        this.emailConfig = emailConfig;
    }

    public  void sendMsg(T e) {
        try {
            Email email = initEmail(emailConfig);
            sendData(email, e);
            email.send();
        } catch (EmailException ex) {
            logger.error("=============邮件发送失败============", ex);
        }
    }


    private Email initEmail(EmailConfig emailConfig) throws EmailException {
        Email email = new SimpleEmail();
        email.setHostName(emailConfig.getHost());
        email.setCharset(emailConfig.getDefaultEncoding());
        email.setSmtpPort(25);
        email.setAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
        //email.setSSLOnConnect(true);
        email.setFrom(emailConfig.getFrom());
        email.setSubject(emailConfig.getTitle());

        //email.setMsg(errMsg);
        email.addTo(emailConfig.getTo().split(";"));
        //email.send();

        return email;
    }


    public static void send(Email email) throws EmailException {
        email.send();
    }


    private  void sendData(Email email, T e) throws EmailException {
        if (e instanceof String) {
            email.setMsg((String) e);
        } else if (e instanceof Exception) {
            Exception ex = (Exception) e;
            String errMsg = ex.getMessage() + "\n";
            for (StackTraceElement element : ex.getStackTrace()) {
                errMsg += "\tat " + String.valueOf(element);
            }
            email.setMsg(errMsg);
        }

    }

}

 

使用的地方这样调

@Autowired
private EmailConfig emailConfig;

@Test
public void testSendEmail() {
    try {
        int bigDecimal = 10/0;
    }catch (Exception e){
         new EmailUtil(emailConfig).sendMsg(e);
    }
}

 

你可能感兴趣的:(EmailUtil 邮件发送工具类)