Send mail based on Spring Boot

  • Sending SMS requires SMS API interface such as cloud chip (link)
  • It can be applied in many places, such as mailbox activation after user registration, mailbox sending verification code, etc
  • In javaEE, there is a package for sending mail, and there is an API for sending mail –JavaMail(link).
  • There are special packages for mail delivery in Springboot

Suppose you send an email from qq mailbox to mailbox 163, the general steps are as follows

There are many protocols designed for this process

  • SMTP is called Simple Mail Transfer Protocol, which is an application layer Protocol based on TCP/IP
  • The default port number is 25
  • It defines the communication rules between mail client software and SMTP server and between SMTP server
  • In a nutshell, it’s for sending and receiving email

  • The POP3/IMAP protocol is required when the user logs in to the mailbox client to read the mail
  • POP3 is called Post Office Protocol. It defines communication rules between mail clients and POP3
  • IMAP is a more powerful and similar extension of OPO3, which I won’t go into here

Specific use (take QQ mailbox as an example)

  • Enable POP3/SMTP service in QQ mailbox (disabled by default), go to Settings -> Account to view

  • Generating authorization Code

  • Create a Spring Boot project to introduce dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>  <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>Copy the code
  • Configure basic configuration information in the configuration file
# SMTP server address
spring.mail.host=smtp.qq.com
Protocol typeSpring.mail. protocol= SMTP spring.mail.username= sender email# authorization codePassword = Use the authorization code generated by the sender mailbox spring.mail.default-encoding=UTF-8 spring.mail.port=465# Encryption tool
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
Copy the code
  • Test sending a simple email
    @Autowired
    MailSender mailSender;

    @Test
    public void contextLoads(a) {
        SimpleMailMessage msg = new SimpleMailMessage();
        / / the recipient
        msg.setTo("Recipient email address (specific email address)");
        // The subject of the message
        msg.setSubject("This is a test email.");
        / / the sender
        msg.setFrom("Sender email (specific email address)");
        // The content of the email
        msg.setText("hello mail!");
        mailSender.send(msg);
    }
Copy the code