welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

MailUtil 发送邮件工具类


分类 Java   关键字 分享   标签 java   发布 hongwei  1430128632162
注意 转载须保留原文链接,译文链接,作者译者等信息。  
准备账户信息
private static String host = "smtp.exmail.qq.com"; //腾讯企业邮箱样例
private static String username = "";
private static String password = "";
private static String nick = ""; //昵称
private static JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

初始化mailSender
private static void initialize(JavaMailSenderImpl mailSender, String host, String username, String password) {
mailSender.setHost(host);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties mailProperties = mailSender.getJavaMailProperties();
mailProperties.setProperty("mail.smtp.auth", "true");
}

发送邮件
try{
    MimeMessage mail = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mail, "utf-8");
    helper.setFrom(new InternetAddress(sender.getUsername(), nick)); //发件人昵称
    helper.setTo(toEmail); //收件人
    helper.setSubject(title); //标题
    helper.setText(text, true); //html正文
    logger.info("send email to " + toEmail);
    sender.send(mail);
    logger.info("success to send email to " + toEmail);
}catch(MailException | MessagingException | UnsupportedEncodingException e) {
    logger.warn("fail to send email to " + toEmail, e);
}

增加间隔时间,避免太频繁导致发送失败
private static BlockingQueue<Map<String, String>> pendingEmails = new LinkedBlockingQueue<>();
    public static boolean sendHtmlEmail(String toEmail, String text, String title) {
        Map<String, String> pendingEmail = new HashMap<>();
        pendingEmail.put("toEmail", toEmail);
        pendingEmail.put("title", title);
        pendingEmail.put("text", text);
       
        logger.info("pending to send mail to "+toEmail+", title: "+title);
        pendingEmails.offer(pendingEmail);
       
        return true;
    }
TaskUtil.submitKeepRunning(new Runnable() {
            public void run() {
                try {
                    while(true) {
                        Map<String, String> pendingEmail = pendingEmails.take();

                        String toEmail = pendingEmail.get("toEmail");
                        String title = pendingEmail.get("title");
                        String text = pendingEmail.get("text");
                      
                        //send email and sleep
                        Thread.sleep(TimeUnit.SECONDS.toMillis(NumberUtil.parseLong(GinkgoConfig.getProperty("mail.thread.sleep.seconds"),10L)));
                    }
                } catch (InterruptedException e) {
                    logger.warn("pendingEmails blocking queue exception: ", e);
                }
            }
})