springmvc 实现javamail

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1.spring配置


    
        
        
        
        
        
            
                true
            
        
    
    
        
        
    
 	
    
        
        
        
    

2.java工具类

@Component("mailSenderUtil")
public class MailSenderUtil {
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private SimpleMailMessage simpleMailMessage;
    @Resource
    private TaskExecutor taskExecutor;
    
    /**
     * 构建邮件内容,发送邮件。
     * @param email 收件人邮箱
     * @param content 收件内容
     */
    public void send(String email,String content) {
        this.taskExecutor.execute(new SendMailThread(email,null,content));
    }
    
    //内部线程类,利用线程池异步发邮件。
    private class SendMailThread implements Runnable {
        private String to;
        private String subject;
        private String content;
        private SendMailThread(String to, String subject, String content) {
            super();
            this.to = to;
            this.subject = subject;
            this.content = content;
        }
        @Override
        public void run() {
            sendMail(to, subject, content);
        }
    }
    
    /**
     * 发送邮件
     * @param to        收件人邮箱
     * @param subject   邮件主题
     * @param content   邮件内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
            messageHelper.setFrom(simpleMailMessage.getFrom());
            if (subject != null) {
                messageHelper.setSubject(subject);
            } else {
                messageHelper.setSubject(simpleMailMessage.getSubject());
            }
            messageHelper.setTo(to);
            messageHelper.setText(content, true);
           javaMailSender.send(message);
        } catch (MessagingException  e) {
            e.printStackTrace();
        }
    }
}

3.方法调用

@resource
private MailSenderUtil mailSenderUtil;
...
mailSenderUtil.send("[email protected]", "HelloWorld");

转载于:https://my.oschina.net/u/1266038/blog/795689

你可能感兴趣的:(测试,java,python)