Integrating mail Sending Service in SpringBoot Development Case

Keywords: Spring FreeMarker Thymeleaf network

I remember a note I took last month, [Mail Notification System Revamping of Microsoft Architecture Practice]. ]

At that time, we used open source third-party plug-ins mail and Thymeleaf to do the sending service. Obviously, you need to configure something like this. Trouble!!! After contacting Spring Boot, there is obviously a better solution. We only need to introduce spring-boot-starter-mail module to realize automatic configuration.

Okay, let's get down to brass tacks. (Most of the code in this article is part of the code. See Git for more details.)

development environment

JDK1.7,Maven,Eclipse,SpringBoot1.5.2,spring-boot-starter-mail,spring-boot-starter-thymeleaf,spring-boot-starter-freemarker

Project structure

Introducing dependencies

The following dependencies are introduced into pom.xml in engineering:

       <!-- email -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!-- thymeleaf Template -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- freemarker Template -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

Configure the following in application.properties:

spring.mail.host=smtp.qq.com
spring.mail.username=345849402@qq.com
#Authorization code g, generated in QQ mailbox client modified to their own settings - accounts - Open Services - access to authorization code
spring.mail.password=XXXXXXX
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

#freemarker
spring.freemarker.template-loader-path=classpath:/static/template/
spring.freemarker.enabled=true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false

#thymeleaf
spring.thymeleaf.prefix=classpath:/static/template/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html  
spring.thymeleaf.cache=false

Encapsulated Entities

First, we encapsulate an Email entity, Email.java:

/**
 * Email Encapsulation class 
 * Founder Kebang Network 
 * Established on July 20, 2017
 *
 */
public class Email implements Serializable {
    private static final long serialVersionUID = 1L;
    //Mandatory parameters
    private String email;//Receiver mail
    private String subject;//theme
    private String content;//Mail content
    //Selective filling
    private String template;//Template
    private HashMap<String, String> kvMap;// Custom parameters
    ... ellipsis get set

Business Realization

Now that spring is used, we define an interface IMailService first, and then implement MailService Impl in the spring way.

The following code implements four ways: plain text, rich text (pictures, attachments), Freemarker template and Thymeleaf template.

It should be noted that Velocity was abandoned after springboot 1.4.0, and the official recommendation was to use freemaker. The thymeleaf is implemented by the blogger himself, which is obviously less efficient than freemaker (see the bottom of the article for evaluation and comparison).

@Service
public class MailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSender mailSender;//Executor
    @Autowired
    public Configuration configuration;//freemarker
    @Autowired
    private SpringTemplateEngine  templateEngine;//thymeleaf
    @Value("${spring.mail.username}")
    public String USER_NAME;//sender

    @Override
    public void send(Email mail) throws Exception {
        MailUtil mailUtil = new MailUtil();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(USER_NAME);
        message.setTo(mail.getEmail());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        mailUtil.start(mailSender, message);
    }

    @Override
    public void sendHtml(Email mail) throws Exception {
        MailUtil mailUtil = new MailUtil();
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(USER_NAME);
        helper.setTo(mail.getEmail());
        helper.setSubject(mail.getSubject());
        helper.setText(
                "<html><body><img src=\"cid:springcloud\" ></body></html>",
                true);
        // Send pictures
        File file = ResourceUtils.getFile("classpath:static"
                + Constants.SF_FILE_SEPARATOR + "image"
                + Constants.SF_FILE_SEPARATOR + "springcloud.png");
        helper.addInline("springcloud", file);
        // Send attachments
        file = ResourceUtils.getFile("classpath:static"
                + Constants.SF_FILE_SEPARATOR + "file"
                + Constants.SF_FILE_SEPARATOR + "Focus on Kegang Network to Get More Source Codes.zip");
        helper.addAttachment("Kebang Network", file);
        mailUtil.startHtml(mailSender, message);
    }

    @Override
    public void sendFreemarker(Email mail) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(USER_NAME);
        helper.setTo(mail.getEmail());
        helper.setSubject(mail.getSubject());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("content", mail.getContent());
        Template template = configuration.getTemplate(mail.getTemplate()+".flt");
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(
                template, model);
        helper.setText(text, true);
        mailSender.send(message);
    }
    @Override
    public void sendThymeleaf(Email mail) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(USER_NAME);
        helper.setTo(mail.getEmail());
        helper.setSubject(mail.getSubject());
        Context context = new Context();
        context.setVariable("email", mail);
        String text = templateEngine.process(mail.getTemplate(), context);
        helper.setText(text, true);
        mailSender.send(message);
    }
}

test case

The old driver takes you to drive SpringbootMailApplication.java:

@SpringBootApplication
@ComponentScan(basePackages={"com.itstyle.mail"})
public class SpringbootMailApplication implements CommandLineRunner {
    @Autowired
    private IMailService mailService;
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMailApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Email mail = new Email();
        mail.setEmail("345849402@qq.com");
        mail.setSubject("You little tease");
        mail.setContent("Welcome to Kebang.com");
        mail.setTemplate("welcome");
        mailService.sendFreemarker(mail);
    }
}

Well, no surprise, these four ways should be absolutely no problem, the small partners will wait for the bottom right corner pop window bar.

Finally, a small evaluation was made to compare the time of template generation (1000 cycles).

  • Thymeleaf time: 2686ms
  • Freemarker usage: 498ms

Freemarker template is recommended for comparative testing.

Items: http://git.oschina.net/52itstyle/spring-boot-mail

Posted by CAPTAINCAPSLOCK on Thu, 06 Jun 2019 14:20:51 -0700