Imitation Niuke community development - Chapter 2 Spring Boot practice, development of community login module

Send mail

Mailbox settings - start the client SMTP service

Take Sina email as an example:

Set the service status of POP3/SMTP service in settings to on.

(the full name of SMTP is "SimpleMailTransferProtocol" Simple mail transfer protocol. It is a set of specifications used to transfer mail from source address to destination address, which controls the transfer mode of mail. SMTP protocol belongs to the TCP/IP protocol cluster. It helps each computer find the next destination when sending or transferring letters. SMTP server is the sending mail server that follows the SMTP protocol. Different mail service providers have corresponding SMTP server address, and this address will be provided to you for your convenience when using Foxmail, outlook and other professional mail management software.)

Spring Mail - Import jar package

You can directly copy Maven's dependencies. Go to mvnrepository.com Search Spring Mail and select the corresponding version.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.1.5.RELEASE</version>
</dependency>

Spring Mail - mailbox parameter configuration

# MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=zhouweicheng1999@sina.com
spring.mail.password=6893139532308134
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=tru

Note that the configuration file application Password in properties spring mail. Password needs to be configured as the authorization code generated for the mailbox, otherwise the email cannot be sent. (as for the last three lines of configuration comments, they can also be sent normally. I'm not sure what the function of this is)

Spring Mail - send mail using JavaMailSender

There are three steps:

1. Sender   2, recipient   3, email title and content

  • Write a MailClient tool class to send mail
  • Open logger log
  • Inject JavaMailSender (managed by Spring container)
  • Sender from injects username # into Bean from configuration file
  • Write a public method to send mail and pass in parameters: recipient to, Title subject and content
  • Build MimeMessage
  • Set the sender, recipient, title and content through MimeMessageHelper. setText plus the second parameter true indicates that html text is supported
@Component
public class MailClient {

    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

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

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("Failed to send mail" + e.getMessage());
        }
    }

}

Test sending email (two test methods are sending normal text and sending Html text respectively):

//@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Qualifier("templateEngine")
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail() {
        mailClient.sendMail("zhouweicheng1999@qq.com", "Test", "zwcnb!");
    }

    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "Zhou Weicheng");
        String content = templateEngine.process("/mail/demo", context);
        mailClient.sendMail("zhouweicheng1999@qq.com", "Html", content);
    }

}

The steps of generating Html text are as follows:

  • Create a new mail template
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Mail example</title>
</head>
<body>
    <p>Welcome,<span style="color:red" th:text="${username}"></span>!</p>
</body>
</html>
  • Auto assemble TemplateEngine
  • Pass the reference Context to the template and set its parameters
  • Call the process method of the template engine and specify its template and data
  • Accept the dynamic web page generated by it, that is, string

Posted by xwhitchx on Mon, 16 May 2022 15:06:31 +0300