This article starts with the problem encountered in mailbox registration verification through JavaMailSender, and analyzes the principles and solutions to the problems in detail.
Using email registration verification, we need to clarify the design ideas:
Question 1: After submitting the registration information, you need to send an email to the email number you filled in.
Question 2: How does the user activate when the email arrives, whether to request the get or obtain the verification code (this article uses the get interface to activate it)
Question 3: How to set the valid time for email activation
Through the above three questions, the blogger will help everyone master JavaMailSender mailbox verification
Question 1
I first need to solve how to send emails to the specified mailbox number
Add the following dependencies to the pom:
<!--email--><dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version></dependency>
That's right, we use javax to expand the mail dependencies in the package, so don't choose the wrong import in the code.
This code is simple and easy for everyone to understand
From top to bottom, let's look at the interface first:
@RequestMapping(value = "myajaxRegister") @ResponseBody public String sendEmail(@RequestParam String email){ User user = new User("luxiaotao","0331"); new Thread(){ @Override public void run(){ emailService.senEmail(user,email); } }.start(); return "The email has been sent to your email address, please activate"; }Because it is a test, the blogger has created fake data from users, and getting email is the key
Create a new thread to execute the mail sending method to improve the user's experience
Imagine if it is not asynchronous, the user needs to wait for the email to be sent before the page will be redirected.
Let’s take a look at the business layer method of sending emails:
@Override public boolean senEmail(User user,String email) { try { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.163.com"); mailSender.setUsername("Fill in your 163 mailbox account"); mailSender.setPassword("163 mailbox password"); MimeMessage mailMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true,"GBK"); helper.setFrom(mailSender.getUsername()); helper.setTo(email); helper.setSubject("title"); helper.setText("Mail sending successfully"); String emailToken = getEmailToken(user); String url = "<a href='http://localhost:8088/activateMail?emailToken="+emailToken+"'>Activate"+"</a></br><h1>If the above hyperconnection cannot be accessed, please copy the following URL to the browser address bar</h1><h2>http://localhost:8088/activateMail?emailToken="+emailToken+"</h2>"; helper.setText(url,true); mailSender.send(mailMessage); return true; } catch (Exception e){ e.printStackTrace(); return false; } } This method explains:
1. If your server mailbox is a qq mailbox, modify it to: mailSender.setHost("smtp.qq.com");
2.MimeMessageHelper is an extension class for mail under javax. If you use spring encapsulated mail, you do not need it. If you use spring mail, the set method will be different
3. The second parameter true of helper.setText(url,true); means that the current String is in html format, so the tags will work
4. getEmailToken(user); method will be discussed below
So far, the email can be sent normally. For the sake of convenience, I give the html page code:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><form method="get" action="/myajaxRegister"> email<input type="text" name="email"></br> <input type="submit" value="register"></form></body></html>
Question 2
How to activate mail using the get requested API?
In question 1, getEmailToken(user) under senEmail() is used to activate
It can be seen that the email content sent by senEmail() is a hyperlink, which is used to start our activation interface.
But what does this have to do with getEmailToken(user)
As can be seen from the literal meaning, we will use a token here
First look at the activation controller
@RequestMapping(value = "activateMail") public String activateMail(@RequestParam String emailToken){ if (emailService.balanceToken(emailToken)){ return "success"; } return "error1"; } Through the hyperlink, we send an emailToken parameter to the server
After the server gets this token, it will compare with the local token. If the same is true, it will pass verification.
Here I use redis to cache, and use token as key and user information (User) as value
Let’s see two methods:
@Override public String getEmailToken(User user){ String token = UUID.randomUUID().toString(); String value = user.toString(); redisTemplate.opsForValue().set(token,value); return token; } @Override public boolean balanceToken(String emailToken) { if(redisTemplate.opsForValue().get(emailToken)!=null){ return true; } return false; } The first method uses redis to convert User information into String and store it in memory
The second method is to activate verification, and use key (Token) to check whether there is a value in redis, and successfully return true.
Question 3
So what if you set the validity period of email verification?
Having said that, students who often use redis probably have guessed it
Just add a line of code to getEmailToken() :
@Override public String getEmailToken(User user){ String token = UUID.randomUUID().toString(); String value = user.toString(); redisTemplate.opsForValue().set(token,value); redisTemplate.expire(token,60, TimeUnit.SECONDS); return token; } Yes, use redisTemplate.expire() to set the expiration time of the current key-value pair
Finally, let’s take a look at the activation email:
The above is the entire content of JavaMailSender's implementation of email registration verification introduced this time. If you still don't understand, you can discuss it in the message area below.