Send e-mail using a spring boot
When the user registration, send a message to the user, allowing users to iodine link in the message to complete the account activation!
Send e-mail client code
package com.nowcoder.community.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Component public class MailClient { private static final Logger logger = LoggerFactory.getLogger(MailClient.class); @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String from; /*** * * @param to 发送邮件给谁? * @param subject * @param content */ public void sendMail(String to, String subject, String content) { try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { logger.error("发送邮件失败:" + e.getMessage()); } } }
springboot mail related configuration
application.properties
MailProperties # spring.mail.host = smtp.sina.cn spring.mail.port = 465 [email protected] # 0fcd058d89ee14a8 (client authorization code) # NOTE: Sina-mail client open after authorization code use only the authorization code login, password authentication can not be used spring.mail.password = 0fcd058d89ee14a8 spring.mail.protocol = SMTPS spring.mail.properties.mail.smtp.ssl.enable to true =
Unit test classes
package com.nowcoder.community; import com.nowcoder.community.util.MailClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = CommunityApplication.class) public class MailTests { @Autowired private MailClient mailClient; @Autowired private TemplateEngine templateEngine; @Test public void testTextMail() { mailClient.sendMail("[email protected]", "TEST", "Welcome."); } @Test public void testHtmlMail() { Context context = new Context(); context.setVariable("username", "sunday"); String content = templateEngine.process("/mail/demo", context); System.out.println(content); mailClient.sendMail("[email protected]", "HTML", content); } }
Test results
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.5.RELEASE) 2020-03-22 15:55:32,814 INFO [main] c.n.c.MailTests [StartupInfoLogger.java:50] Starting MailTests on lzph-pc with PID 8360 (started by admin in E:\nowcoder\nowcoder-workspace\community-2.1) 2020-03-22 15:55:32,817 DEBUG [main] c.n.c.MailTests [StartupInfoLogger.java:53] Running with Spring Boot v2.1.5.RELEASE, Spring v5.1.7.RELEASE 2020-03-22 15:55:32,819 INFO [main] c.n.c.MailTests [SpringApplication.java:675] No active profile set, falling back to default profiles: default 2020-03-22 15:55:40,542 INFO [main] o.s.s.c.ThreadPoolTaskExecutor [ExecutorConfigurationSupport.java:171] Initializing ExecutorService 'applicationTaskExecutor' 2020-03-22 15:55:41,497 INFO [main] o.s.b.a.w.s.WelcomePageHandlerMapping [WelcomePageHandlerMapping.java:61] Adding welcome page template: index 2020-03-22 15:55:42,665 INFO [main] c.n.c.MailTests [StartupInfoLogger.java:59] Started MailTests in 11.173 seconds (JVM running for 13.768) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>邮件示例</title> </head> <body> <p>欢迎你, <span style="color:red;">sunday</span>!</p> </body> </html> 2020-03-22 15:55:50,367 INFO [Thread-3] o.s.s.c.ThreadPoolTaskExecutor [ExecutorConfigurationSupport.java:208] Shutting down ExecutorService 'applicationTaskExecutor'