Email service has been a basic service, is one of the necessary functions of the website, when registering some websites, the mailbox will usually receive a successful registration notification email or click to activate the account email, the same is true of the blog park. This paper uses Spring Boot to send a notification email through QQ mailbox to imitate blog Park.
The subject email “Welcome to join the Blog Park” sent by the blog Park is shown in the picture. This type of notification message, only the login user name changes, the other message content is unchanged, is suitable for the mail template processing.
Templates can realize the separation of display and data, template files and data through the template engine to generate the final HTML code.
Thymeleaf is a modern server-side Java template engine for Web and standalone environments, capable of handling HTML, XML, JavaScript, CSS and even plain text. Thymeleaf uses tag attributes as syntax to render template pages directly in the browser. Compared to other template engines such as Freemaker, Thymeleaf can open template pages directly in the browser and display them correctly, without having to launch the entire Web application.
Thymeleaf is an official template engine recommended by Spring. Spring Boot is friendly to Thymeleaf and the configuration is simple. Thymeleaf is used as the template engine here.
The following formal start to achieve imitation blog park to send notification mail.
1. Pom.xml adds mail and template-related 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>
Copy the code
2. Application. property Configures the mailbox and Thymelea template
I use QQ mailbox and need to obtain the authorization code of QQ mailbox.
On QQ email generated code: enter QQ inbox – > Settings – > account – > POP3 / IMAP/SMTP/Exchange/CardDAV CalDAV service – > generate the authorization code – > send phone validation messages – > get authorization code
Spring.mail.host=smtp.qq.com spring.mail.username=QQ mailbox spring.mail.password= authorization code spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true Spring. The mail. The properties. The mail. The SMTP. Starttls. Required = true # thymelea template configuration spring. The thymeleaf. Prefix = classpath: / templates / spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 Spring. Thymeleaf. Servlet. The content-type: text/HTML # hot deployment file, page does not produce the cache, Update spring. Thymeleaf. Cache = false spring. The resources. The chain. The strategy. The content. enabled = true spring.resources.chain.strategy.content.paths=/**Copy the code
3. Write Service and its implementation
There are two methods in a Service:
SendSimpleMail is a more basic example for sending simple text messages.
SendHtmlMail is used to sendHtmlMail, and this method is used to send notification mail. Template mail is a subclass of HTML mail.
MailService:
public interface MailService {
public void sendSimpleMail(String to, String subject, String content);
public void sendHtmlMail(String to, String subject, String content);
}
Copy the code
MailServiceImpl:
@Component
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);// The recipient of the message
message.setSubject(subject);// The subject of the message
message.setText(content);// The content of the email
try {
mailSender.send(message);
logger.info("Sending simple email succeeded!");
} catch (Exception e) {
logger.error("An exception occurred while sending simple mail!", e); }}@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true indicates that a multipart message needs to be created
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("HTML email sent successfully!");
} catch (MessagingException e) {
logger.error("Exception occurred while sending HTML mail!", e); }}}Copy the code
4. Create a template
Resorces /templates create the emailtemplate. HTML template corresponding to the spring.thymeleaf.prefix=classpath:/templates/ template configuration, otherwise the template will not be found.
Here is a brief introduction to the use of Thymeleaf:
Introduce namespaces:. The same tag name with different meanings may appear in different constraint documents, and the introduction of namespaces can avoid confusion and conflict.
Access data: # {user.name}
Access variable: ${today}
Output URL: blog garden
For more detailed instructions and rules, see: Thymeleaf official documentation
EmailTemplate. HTML:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Welcome to join the blog Park</title>
</head>
<body>
<p>Hello, your account in blogpark has been activated successfully. Your login user name is:<span th:text="${username}"></span>.</p>
<p>--</p>
<div>Blog garden (<a th:href="@{https://www.cnblogs.com }">www.cnblogs.com</a>) - an online home for developers</div>
<p>Code changes the world!</p>
</body>
</html>
Copy the code
5. JUnit unit tests
Unit testing with Junit, which is configured by default in POM.xml, requires writing test classes and test methods. The Test class is named xxxtest.java, and the Test method can be used with the @test annotation. The specific code is as follows:
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testSendSimpleMail(a) throws Exception {
mailService.sendSimpleMail("[email protected]"."Test sending simple text emails"."Test sending simple text emails");
}
@Test
public void testSendTemplateMail(a) {
Context context = new Context();
context.setVariable("username"."shangguanhao");
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail("[email protected]"."Welcome to the Blog Park.", emailContent); }}Copy the code
With the Junit test, you can send a simple text message and an HTML template message, almost exactly like the blog garden (as shown below) :
Full code: GitHub address
Reference: SpringBoot (10) : Mail service