Spring Boot (twelve): Spring Boot mail service

The earliest is when we send an email to send mail using JavaMail, and in the Spring Boot, Spring Boot JavaMail will help us a good package, can be directly used to use.

1. dependent files pom.xml

Listing: the Spring-the Boot-mail / pom.xml
***

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
  • spring-boot-starter-thymeleaf introduced this template engine is because when we send mail, use a variety of formats HTML way easier to implement, we can use the same freeMark, Spring Boot dependent package also provides for us.

2. Profiles application.yml

Listing:
***

server:
  port: 8080
spring:
  application:
    name: spring-boot-mail
  mail:
    host: smtp.qq.com
    username: 136736247
    password: xxxxxx
    default-encoding: UTF-8
    fromAddr: [email protected]
    nickName: inwsy

Here I use the QQ mailbox as a mail sender, which passwordis not our QQ password, which we need in the QQ mailbox set up inside their own application. As shown below:

Where spring.mail.fromAddrand spring.mail.nickNamethese two configurations is my own configuration, the configuration is not official, I will read the follow-up of these two configuration items in the code.

3. Simple Mail sent

3.1 implementation class

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java
***

@Service
public class MailServiceImpl implements MailService {

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

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.fromAddr}")
    private String from;

    @Value("${spring.mail.nickName}")
    private String nickName;

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(nickName + "<" + from + ">");
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        
        try{
            javaMailSender.send(simpleMailMessage);
            logger.info("简易邮件发送成功");
        } catch(Exception e) {
            logger.error("简易邮件发送异常", e);
        }

    }
}

3.2 Test class

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java
***

@Autowired
MailService mailService;

@Test
public void sendSimpleEmail() {
    mailService.sendSimpleEmail("[email protected]", "测试邮件题目", "测试邮件内容");
}

Here the message is sent to the Hotmail mailbox himself.

4. E-mail in HTML format

4.1 implementation class

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java
***

@Override
public void sendHTMLEmail(String to, String subject, String content) {
    MimeMessage message = javaMailSender.createMimeMessage();

    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

        messageHelper.setFrom(new InternetAddress(from, nickName, "UTF-8"));
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(content, true);

        javaMailSender.send(message);
        
        logger.info("HTML 模版邮件发送成功");
    } catch (MessagingException e) {
        logger.error("HTML 模版邮件发送失败", e);
    } catch (UnsupportedEncodingException e) {
        logger.error("收件地址编码异常", e);
    }

}

4.2 page template

Listing: the Spring-the Boot-mail / src / main / Resources / Templates / email.html
***

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>邮件模版</title>
    </head>
    <body>
        这是邮件模版生成的邮件,可以点击链接查看详情。
        <a href="#" th:href="@{ http://www.geekdigging.com/ }">查看详情。</a>
        当前的Code为:<span th:text="${code}"></span>
    </body>
</html>

Here we add dynamic content code, in the daily development, we used to send a verification code, dynamically generated content is necessary.

4.3 test class

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java
***

@Test
public void sendHTMLTemplateMail() {
    Context context = new Context();
    context.setVariable("code", "123456");
    String emailHTMLContent = templateEngine.process("email", context);

    mailService.sendHTMLEmail("[email protected]", "测试 HTML 模版邮件", emailHTMLContent);
}

5. E-mail with attachments

5.1 implementation class

代码清单:spring-boot-mail/src/main/java/com/springboot/springbootmail/service/impl/MailServiceImpl.java
***

@Override
public void sendAttachmentsMail(String to, String subject, String content, String fileName, String filePath) {

    MimeMessage message = javaMailSender.createMimeMessage();

    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

        messageHelper.setFrom(new InternetAddress(from, nickName, "UTF-8"));
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(content, true);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        messageHelper.addAttachment(fileName, file);

        javaMailSender.send(message);
        
        logger.info("带附件邮件发送成功");
    } catch (MessagingException e) {
        logger.error("带附件邮件发送失败", e);
    } catch (UnsupportedEncodingException e) {
        logger.error("收件地址编码异常", e);
    }
}

Note: multiple If you need to send multiple attachments, write messageHelper.addAttachment(fileName, file);to.

5.2 test class

代码清单:spring-boot-mail/src/test/java/com/springboot/springbootmail/SpringBootMailApplicationTests.java
***

@Test
public void sendAttachmentsMail() {

    String fileName = "图片.jpg";
    String filePath = "C:\\Users\\inwsy\\Downloads\\0370279582fe3e2a8012060c896a5dd.jpg";

    mailService.sendAttachmentsMail("[email protected]", "测试带附件的邮件", "详细请查阅附件", fileName, filePath);
}

6. Summary

In the actual development process, the message failed to send what is a relatively frequent, such as: network congestion, the other rejected, etc., usually in the design data messaging system, you can first write data to be transmitted, etc. then modify the transmission completion flag, and then add a guarantee mechanism, for example, increasing a timed task, the period of time, and retry transmission failure less than a certain threshold number of times the content is transmitted again, the mail system if the pressure is too large, may be selected used to transmit asynchronous manner, such as using message queues pressure.

7. Sample Code

Sample Code -Github

Sample Code -Gitee

7. References

http://www.ityouknow.com/springboot/2017/05/06/spring-boot-mail.html

Guess you like

Origin www.cnblogs.com/babycomeon/p/11669486.html