Blog address: program ape Liu Chuanfeng

Blog gitHub source address: github.com/liujianview…

Blog gitee source address: gitee.com/liuchuanfen…

Welcome to give a star encouragement ~

A preface.

When thinking about blog planning, I think there should be a user registration function, so that users can comment on blog posts, can also like private bloggers, and have their own background. If you forget your password, you can reset it. In this case, you need to send a verification code. In this case, YOU can send a verification code by email (you can also send a verification code by SMS, but you have to pay for the short message number, be frugal ~). More convenient can access QQ one-click login, very convenient, the subsequent article will be a tutorial, this time to introduce how to use QQ email to send verification code (other email).

2. Enable the QQ mailbox IMAP service

First of all, click login QQ mailbox to enter the QQ mailbox home page, click Settings – account

Scroll down to the middle to find the IMAP/SMTP service

After the IMAP/SMTP service is enabled and authenticated, a string of ciphertext passwords will be displayed (copied and saved, which will be put in the configuration file later).

Three. Code implementation

1. Pom file import supports email dependency

<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>Copy the code

2. The configuration file application.properites adds the mailbox configuration information

Add the following at the end of the configuration file

# spring.mail.host=smtp.qq.com # spring.mail.username= XXXX@qqCom #IMAP/SMTP server ciphertext authorization code spring.mail.password= XXXX spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
Copy the code

3. Specific implementation code

My idea is to randomly generate the verification code and put it into redis cache, set the validity period of 5 minutes, take it out of Redis and compare it with the user input value when using it, and then give the response prompt, the code is as follows:

/ * * *@description: Sends an email to obtain the verification code *@author: liuchuanfeng
 * @time: 2020/12/8 15:52 * /
@RestController
@Slf4j
public class GetEmailCodeController {

    @Autowired
    StringRedisServiceImpl stringRedisService;

    @Autowired
    JavaMailSender mailSender;// Inject the bean that sends the mail

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

    // Define the title to send
    public static String title="[Program ape Liu Chuan-feng] obtain captcha code";

    / * * *@description: Sends the verification code * to the specified mailbox@param email
     * @return: java.lang.String
     * @author: liuchuanfeng
     * @time: 2020/12/8 shew forth * /
    @PostMapping(value = "/getCode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getEmail(@RequestParam("email") String email) {
        try {
            String body = setEmailBody(email);
            MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom(emailUserName);// Set a qq mailbox
            message.setTo(email);		// Set the recipient
            message.setSubject(title);	// Set the title
            message.setText(body);  	// The second argument, true, indicates that the mail is written in HTML
// FileSystemResource file = new FileSystemResource(
// File File = new File(" File path ");
// helper.addattlove (" image.jpg ", file); // Helper.addattlove (" image.jpg ", file); // Add messages with attachments
// helper.addInline("picture",file); // Add a message with static resources
            log.info("getEmail send email message: [{}]", message);
            this.mailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("[{}] send email message exception", email, e);
            return JsonResult.fail().toJSON();
        }
        return JsonResult.success().toJSON();
    }

    private String setEmailBody(String email){
        // Obtain the mailbox random verification code
        String emailCode = EmailRandomUtil.randomNumBuilder();
        // Save the mailbox verification code in Redis and set the expiration time
        stringRedisService.set(email, emailCode);
        stringRedisService.expire(email, 300);
        StringBuffer body = new StringBuffer();
        body.append("Here you are, guest officer. Please come inside! \n\n").append("Your verification code is:").append(emailCode+"\n\n");
        body.append("Please note: the verification code will be invalid if you use it within 5 minutes after receiving the email. \n\n");
        returnbody.toString(); }}Copy the code

Generate the 6-digit random verification code as follows:

/ * * *@description: Email generates verification code *@author: liuchuanfeng
 * @time: 2020/12/8 15:56 * /
public class EmailRandomUtil {

    public static String randomNumBuilder(a){

        String result = "";
        for(int i=0; i<6; i++){ result += Math.round(Math.random() *9);
        }

        returnresult; }}Copy the code

4. To summarize

Using SpringBoot mailbox to send verification code is very simple, the general process is as follows:

  1. Log in to QQ mailbox to enable the IMAP service and obtain your ciphertext authorization code
  2. SpringBoot poM file to add mailbox dependencies
  3. Add authorization codes and other information to the SpringBoot configuration file
  4. Call the random number code, concatenate the parameters and send them to the specified mailbox and save them to Redis

More wonderful features please pay attention to my personal blog site: liujian.cool

Welcome to my personal public account: Program ape Liu Chuanfeng