java to implement mailbox verification (a simplified operation and idea, many things must be read)

I don't know what email verification is all the time. I always think it's amazing (because I almost never use email) that this function has been successfully implemented under the leadership of the big guy. I don't need to say much to start the operation:

Technology I use:

java,maven,mysql, some related dependencies and jar packages

Because I use QQ mailbox, I need to unlock some QQ mailbox services:

Log in QQ email, and open POP3/SMTP service in settings - > account panel:

Be careful!
After the service is enabled, an authorization code will be obtained, which is very important

Let's talk about the process first

1. Fill in the information on the registration page and click the registration button

2. The background controller receives the data and judges whether the data is filled in correctly. If the user data is saved correctly and the user is not activated

3. Send email to the user to activate the account

4. After the user is activated successfully, change the user's status to the activated status

Next, start the code operation:

Create a maven project

Here we need a JavaMail coordinate (other coordinates are different from each other, so I won't put them up)

		<!-- I used 1.5.0 Version -->

You also need a jar package of JavaMail to put in the shared module for use. Here is the JavaMail Code:

public class MailUtil implements Runnable{
    private String email;// Recipient mailbox
    private String emailKey;// Activation code

    public MailUtil(String email, String emailKey) { = email;
        this.emailKey = emailKey;

    public void run() {
        // 1. Create connection object javax.mail.Session
        // 2. Create mail object javax.mail.Message
        // 3. Send an activation email
        String from = "Your QQ";// Sender email
        String host = ""; // Specify the host of sending mail, (QQ) 𞓜 (Netease)

        Properties properties;// Get system properties
        properties = System.getProperties();

        properties.setProperty("", host);// Set up mail server
        properties.setProperty("mail.smtp.auth", "true");// Open authentication

        try {
            //QQ mailbox needs the following code, 163 mailbox does not need
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            // 1. Get the default session object
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("Your QQ", "You just activated POP3 Activate code here"); // Sender's email account and authorization code

            // 2. Create mail object
            Message message = new MimeMessage(session);
            // 2.1 set sender
            message.setFrom(new InternetAddress(from));
            // 2.2 set receiver
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3 set mail subject
            message.setSubject("Account activation");
            // 2.4 setting mail content
            String content = "<html><head></head><body><h1>This is an activation email,Please click the following link for activation</h1><h3><a href='http://localhost:8080/user/registerAllow?emailKey="
                    + emailKey + "'>http://localhost:8080/user/registerAllow?emailKey=" + emailKey 
                    + "</href></h3></body></html>";
            message.setContent(content, "text/html;charset=UTF-8");
            // 3. Send email
            System.out.println("Message sent successfully!");
        } catch (Exception e) {

Create a database table

	username VARCHAR(50),			#User account
	PASSWORD VARCHAR(50),			#User password
	email VARCHAR(100),			#E-mail
	emailKey VARCHAR(50),			#Generated random activation key
	emailKeyTime INT,		#Effective verification time of mailbox activation

Create a registration page

Basically that's all, and then we go back to the background:

Code of my controller layer method (two in total, the first is responsible for registration and the second is responsible for activation):

    public BaseResult register(@RequestBody User user){
        if (user.getUsername().equals("") || user.getEmail().equals("")){
            return BaseResult.error("Incomplete data filling");
            return BaseResult.error("Mailbox format error");
        try {
        } catch (Exception e) {
            return BaseResult.error(e.getMessage());
        return BaseResult.ok("login was successful");
    public void emailBeUse(@RequestParam("emailKey") String emailKey){
        //Check the database to see if it can match the user with the activation code
        try {
        } catch (Exception e) {

My service layer method code:

	public void register(User user) {
        //Look up the database to see if there is the same user data
        User u = userDao.selectOne(user);
        if (u != null){
            //Find the same user name and prompt that it is registered
            throw new RuntimeException("User name registered");
        //Unregistered users need to generate mailbox activation code for mailbox verification
        String code = EmailUtils.getCode();
        //Save user to database, display inactive user
        //Save activation code
        //Save activation code effective time (in the method, I let him wait ten minutes)
        try {
            //Storage user
        } catch (Exception e) {
            //Failed to save user
        //After saving the user, send a message to the user by thread
        new Thread(new MailUtil(user.getEmail(),user.getEmailKey())).start();
    public void registerAllow(String emailKey) {
        //Query all users to see if there is matching information
        User user = null;
        user = userDao.selectWithEmailKey(emailKey);
        if (user == null){
            throw new RuntimeException("The user is not registered,No activation code present");
            //If the user is found, you need to identify whether his activation time has exceeded the time limit
            Long emailKeyTime = user.getEmailKeyTime();
            Long newTime = new Date().getTime();
            if ((newTime - emailKeyTime) > (1000*60*10)){
                throw new RuntimeException("User activation code timeout,Please re register");
                //Activation successfully modified user status
                //Jump to login page

EmailUtils in my method is a tool class used to generate activation code

The operation is almost finished here. Please solve the details by yourself. The following is the illustration:



Activation completed

38 original articles published, 19 praised, 3670 visited
Private letter follow

Tags: Session Database Maven SSL

Posted on Thu, 06 Feb 2020 23:52:16 -0800 by dch27