Spring Boot 集成 Email、Velocity 多线程发送 邮件

邮件发送

邮件发送基本涉及到各种系统,是研发中必不可少的技能。一直连续做了好多次邮件发送,整理如下:

需要依赖

    
        org.springframework.boot
        spring-boot-starter-mail
    
    
    
        org.apache.velocity
        velocity
        1.7
    

项目结构如下Spring Boot 集成 Email、Velocity 多线程发送 邮件_第1张图片

##模板 :

 <div>
    <h1>
        <div>${message}div>
    h1>
div>

配置文件

#spring.mail.host = smtphm.qiye.163.com
spring.mail.host = smtp.qiye.163.com
spring.mail.username = # 用户名
spring.mail.password = #授权码
spring.mail.port = 465
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.smtp.starttls.required = true
spring.mail.properties.mail.smtp.timeout = 30000
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug = false
spring.mail.default-encoding = UTF-8

实现代码

多线程类

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

/**
 * @author li-jc
 * @version 1.0.0
 * @className MailTask
 * @description 线程类
 * @date 2019/12/5 14:24
 * @since JDK 1.8
 */
@Slf4j
public class MailTask implements Runnable {
    private String from;
    private String to;
    private String subject;
    private String content;
    private JavaMailSender sender;

    public MailTask(String from, String to, String subject, String content, JavaMailSender sender) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.sender = sender;
    }

    @Override
    public void run() {
        log.info("send HTML mail thread begin");
        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            sender.send(message);
            log.info("send HTML mail thread end");
        } catch (Exception e) {
            log.error("send HTML mail thread exception!", e);
        }
    }
}

发送邮件线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author li-jc
 * @version 1.0.0
 * @className MailExecutorService
 * @description 发送邮件线程池
 * date: 2018/1/13 14:43 
* @since JDK 1.8 */
public class MailExecutorService { private volatile static ExecutorService executorService; public static ExecutorService getExecutorService(){ if (executorService == null) { synchronized (MailExecutorService.class){ if (executorService == null) { executorService = Executors.newFixedThreadPool(20); } } } return executorService; } }

邮件服务

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.concurrent.ExecutorService;

/**
 * @author li-jc
 * @version 1.0.0
 * @className MailExecutorService
 * @description 发送邮件
 * date: 2018/1/12 14:43 
* @since JDK 1.8 */
@Slf4j @Service public class MailService { @Autowired private JavaMailSender sender; @Value("${spring.mail.username}") private String from; /** * 发送纯文本的简单邮件 * @param to * @param subject * @param content */ public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("城云产品三部<"+ from +">"); message.setTo(to); message.setSubject(subject); message.setText(content); try { sender.send(message); log.info("简单邮件已经发送。"); } catch (Exception e) { log.error("发送简单邮件时发生异常!", e); } } /** * 发送html格式的邮件 * @param to * @param subject * @param content */ public void sendHtmlMail(String to, String subject, String content){ try { log.info("send HTML mail start"); ExecutorService executorService = MailExecutorService.getExecutorService(); executorService.execute(new MailTask("城云产品三部<"+ from +">",to,subject,content,sender)); log.info("send HTML mail end"); } catch (Exception e) { log.error("send HTML mail exception", e); } } /** * 发送带附件的邮件 * @param to * @param subject * @param content * @param filePath */ public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = sender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("城云产品三部<"+ from +">"); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); sender.send(message); log.info("带附件的邮件已经发送。"); } catch (MessagingException e) { log.error("发送带附件的邮件时发生异常!", e); } } /** * 发送嵌入静态资源(一般是图片)的邮件 * @param to * @param subject * @param content 邮件内容, * 需要包括一个静态资源的id,比如: * @param rscPath 静态资源路径和文件名 * @param rscId 静态资源id */ public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = sender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("城云产品三部<"+ from +">"); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); sender.send(message); log.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { log.error("发送嵌入静态资源的邮件时发生异常!", e); } } }

封装邮件基础服务

import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

/**
 * 基础服务
 * Created by lijc on 2017-10-02
 */
@Slf4j
@Service
public class BaseService {

    @Resource
    private MailService mailService;

    @Resource
    private Environment environment;



    /** 发送测试邮件
     * eg :templatePath email/test.vm
     * */
    public boolean sendTestEmail(final String email,final  String message, final String templatePath ) {
        Properties p = new Properties();

        // 加载 classpath 目录下的 vm 文件
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");

        Velocity.init(p); // 初始化

        VelocityContext context = new VelocityContext();

        context.put("message", message);

        StringWriter writer = new StringWriter();
        Template template = Velocity.getTemplate(templatePath);

        template.merge(context, writer);

        String html = writer.toString();

        try {
            writer.close();
        } catch (IOException e) {
            log.error("Close StringWriter Exception: {}", e.getMessage());
        }

        mailService.sendHtmlMail(email, "【产品三部】测试邮件", html);

        return true;
    }

}

总结:完整的实现了邮件发送功能,采用了自定义模板、多线程发送。如有不妥之处希望留言。如果想方便每次都能直接用可以结合springboot-starter,做成集成的启动类,能直接调用。

你可能感兴趣的:(JAVA,项目集成)