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)

<dependencies>
		<!-- I used 1.5.0 Version -->
       <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
            <scope>compile</scope>
        </dependency>
</dependencies>

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) {
        this.email = email;
        this.emailKey = emailKey;
    }

    @Override
    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 Number@qq.com";// Sender email
        String host = "smtp.qq.com"; // Specify the host of sending mail, smtp.qq.com (QQ) 𞓜 smtp.163.com (Netease)

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

        properties.setProperty("mail.smtp.host", 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();
            sf.setTrustAllHosts(true);
            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 Number@qq.com", "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
            Transport.send(message);
            System.out.println("Message sent successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Create a database table

user
CREATE TABLE USER (
	uid INT PRIMARY KEY AUTO_INCREMENT,	#User ID
	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):

	//register
	@PostMapping("/register")
    public BaseResult register(@RequestBody User user){
        if (user.getUsername().equals("") || user.getEmail().equals("")){
            return BaseResult.error("Incomplete data filling");
        }
        if(!user.getEmail().matches("^\\w+@(\\w+\\.)+\\w+$")){
            return BaseResult.error("Mailbox format error");
        }
        try {
            userServiceImpl.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.error(e.getMessage());
        }
        return BaseResult.ok("login was successful");
    }
    //activation
    @GetMapping("/registerAllow")
    public void emailBeUse(@RequestParam("emailKey") String emailKey){
        //Check the database to see if it can match the user with the activation code
        try {
            userServiceImpl.registerAllow(emailKey);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

My service layer method code:

	//register
	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
        user.setState(0);
        //Save activation code
        user.setEmailKey(code);
        //Save activation code effective time (in the method, I let him wait ten minutes)
        user.setEmailKeyTime(EmailUtils.getKryEndTime());
        try {
            //Storage user
            userDao.insert(user);
        } catch (Exception e) {
            //Failed to save user
            e.printStackTrace();
        }
        //After saving the user, send a message to the user by thread
        new Thread(new MailUtil(user.getEmail(),user.getEmailKey())).start();
    }
    //activation
    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");
        }else{
            //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)){
                //overtime
                throw new RuntimeException("User activation code timeout,Please re register");
            }else{
                //Activation successfully modified user status
                user.setState(1);
                userDao.updateByPrimaryKey(user);
                //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:

Database:


Database:

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