JavaMail Implementing a registered mailbox verification case

Source: Internet
Author: User
Tags connection pooling email string email account

In daily life, when we register an account in a website, often after submitting personal information, the website also wants us to verify by mobile phone or mail, the message will probably look like this:

Users can sign in by clicking the link to complete the registration.

Maybe you wonder why it's so troublesome to submit a registration directly? This is a large part of the reason for preventing malicious registration. Let's go ahead and use the simplest jsp+servlet way to complete a small case of email verification registration.

Preparatory work
Prerequisite knowledge
Before you get started, you might want to know something about the following:

(1) JSP and servlet
(2) MySQL
(3) C3P0
(4) SMTP protocol and POP3 protocol
If the mail sending and receiving process completely do not understand, can spend three minutes to MU class network to understand, speak is very clear, here will not repeat. Put sketch recall:

Mail sending and receiving process
Mailbox Preparation
After understanding the above, to achieve this case, first we have to have two mailbox account, one for sending mail, one to receive mail. This case uses QQ mailbox to send activation mail to 163 mailbox, so we need to login QQ mailbox, open the POP3/SMTP service in the settings----account panel to allow us to send mail through a third party client:

Also note that login to the following services: Pop3/imap/smtp/exchange/carddav/caldav service, need to use the authorization code instead of the QQ password, authorization code is used to log in to the third-party mail client's private password. So we need to get the authorization code to use in later programs.

Well, it's almost ready for the job, so let's get started.

Implement registration Demo
Start by creating a Dynamic Web project that introduces the necessary jar packages
C3p0-0.9.1.2-jdk1.3.jar
Mail.jar
Mysql-connector-java-5.1.41-bin.jar

Create a database table
Next, use MySQL to create a simple user table:

create table `user`(    id int(11) primary key auto_increment comment ‘用户id‘,    username varchar(255) not null comment ‘用户名‘,    email varchar(255) not null comment ‘用户邮箱‘,    password varchar(255) not null comment ‘用户密码‘,    state int(1) not null default 0 comment ‘用户激活状态:0表示未激活,1表示激活‘,    code varchar(255) not null comment ‘激活码‘)engine=InnoDB default charset=utf8;

The place to note is the State field (used to determine whether the user account is active) and the Code field (the activation code).

Create a registration page
Use JSP to create a simple registration page (please ignore the interface yourself):

Well, that's simple enough.

The main business logic
Think about it, our entire process should look like this:

Users fill in the relevant information, click the registration button
The system first saves the user record to the database, where the user state is not activated
The system sends an e-mail message and notifies the user to verify
The user logs into the mailbox and clicks the Activate link
The system changes the user state to activated and notifies the user that the registration was successful
Figuring out the whole process should be easy to implement. Is the package structure that I built:

The complete code is shown in the following link, where only the main ideas are discussed.

First of all, after the user submits the registration information, the corresponding servlet will pass the relevant information to the service layer to process, what needs to be done in the service is to save the record to the database (call the DAO layer), and then send a message to the user, Userserviceimpl related code is as follows:

public boolean doRegister(String userName, String password, String email) {    // 这里可以验证各字段是否为空    //利用正则表达式(可改进)验证邮箱是否符合邮箱的格式    if(!email.matches("^\\[email protected](\\w+\\.)+\\w+$")){        return false;    }    //生成激活码    String code=CodeUtil.generateUniqueCode();    User user=new User(userName,email,password,0,code);    //将用户保存到数据库    UserDao userDao=new UserDaoImpl();    //保存成功则通过线程的方式给用户发送一封邮件    if(userDao.save(user)>0){        new Thread(new MailUtil(email, code)).start();;        return true;    }    return false;}

It should be noted that a new thread should be created to carry out the task of sending mail, otherwise it is not expected to be scolded.
The operation of the database is relatively simple, it is not posted here, nothing more than to insert user records into the database. It is worth mentioning that C3P0 is used here as a data source instead of DriverManager, which is much more efficient when it comes to releasing a database connection frequently, c3p0 the simplest configuration as follows:

<?xml version="1.0" encoding="UTF-8"?><c3p0-config>    <named-config name="mysql">        <property name="driverClass">com.mysql.jdbc.Driver</property>        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test1?useSSL=false</property>        <property name="user">root</property>        <property name="password">123456</property>        <!-- 初始化时一个连接池尝试获得的连接数量,默认是3,大小应该在maxPoolSize和minPoolSize之间 -->        <property name="initialPoolSize">5</property>        <!-- 一个连接最大空闲时间(单位是秒),0意味着连接不会过时 -->        <property name="maxIdleTime">30</property>        <!-- 任何指定时间的最大连接数量 ,默认值是15 -->        <property name="maxPoolSize">20</property>        <!-- 任何指定时间的最小连接数量 ,默认值是3 -->        <property name="minPoolSize">5</property>    </named-config></c3p0-config>

Provide a tool class Dbutil to get, release the connection:

 public class DBUtil {    private static ComboPooledDataSource cpds=null;    static{        cpds=new ComboPooledDataSource("mysql");    }    public static Connection getConnection(){        Connection connection=null;        try {            connection = cpds.getConnection();        } catch (SQLException e) {            e.printStackTrace();        }        return connection;    }    public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){        try {            if(rs!=null){                rs.close();            }            if(pstmt!=null){                pstmt.close();            }            if(rs!=null){                rs.close();            }        } catch (SQLException e) {            e.printStackTrace();        }    }}

It is important to note that even with connection pooling, the Close method is called after the connection is used, which of course does not mean that the TCP connection to the database is closed but the connection is returned to the pool, and if it is not close, the connection will always be occupied. Until the connection in the connection pool is exhausted.

Send mail using JavaMail
Using JavaMail to send mail is simple and three-step:

(1) Create Connection object Javax.mail.Session
(2) Create a Mail object Javax.mail.Message
(3) Send mail
Look directly at the code, detailed comments in the code, the Mailutil code is as follows:

public class Mailutil implements Runnable {private string email;//recipient mailbox private string code;//Activation code public MAILU        Til (string email, string code) {this.email = email;    This.code = code;        } public void Run () {///1. Create a Connection object Javax.mail.Session//2. Create a Mail object Javax.mail.Message//3. Send an activation email string from = "[email protected]";//Sender e-mail string host = "smtp.qq.com"; Specifies the host to send mail smtp.qq.com (QQ) |smtp.163.com (NetEase) Properties Properties = System.getproperties ();//Get System Properties proper        Ties.setproperty ("Mail.smtp.host", host);//Set mail server Properties.setproperty ("Mail.smtp.auth", "true");//Turn on authentication            Try {//QQ mailbox requires 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 Getpasswordauthenticati                On () {return new Passwordauthentication ("[email protected]", "xxx");//Sender email account, Authorization code            }            });            2. Create Message 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 the message subject Message.setsubject ("Account Activation"); 2.4 Setting the message contents String content = "

PS: The above account and authorization code should be modified accordingly.

Once the user submits the registration information, they should be able to receive the verification email when they are done:

After the user clicks on the link, the job we have to do is to change the status of the corresponding user in the database according to code (which can be generated with the UUID) and then prompt the user to register the results.

Summarize
A brief description of how to use JavaMail to complete a registration case with a mailbox verification, of course, there are many details to be noted in the actual development, such as the verification of user submissions, password encryption, etc., the simple case here does not deal with these details in detail.

Source: JavaMail Source code

JavaMail Implementing a registered mailbox verification case

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.