Email certification Process

Source: Internet
Author: User
Tags 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.

Prerequisite knowledge of preparation work

Before you get started, you might want to know something about the following:

    • JSP and Servlet
    • Maven
    • Mysql
    • C3p0
    • 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 delivery 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 Create MAVEN project

This case is based on Maven, so you'll first create a MAVEN Web project and introduce dependencies:

<dependencies><!--java EE dependency--<Dependency><Groupid>javaee</Groupid><Artifactid>javaee-api</Artifactid><Version>5</Version><Scope>test</Scope></Dependency><Dependency><Groupid>taglibs</Groupid><Artifactid>standard</Artifactid><version>1.1.2</Version></Dependency><!--MySQL driver dependent--<Dependency><Groupid>mysql</Groupid><Artifactid>mysql-connector-java</Artifactid><version>5.1.40</Version></Dependency><!--c3p0 Dependent--<Dependency><Groupid>c3p0</Groupid><Artifactid>c3p0</Artifactid><version>0.9.1.2</Version></Dependency><!--javamail related dependencies--<Dependency><Groupid>javax.mail</Groupid><Artifactid>mail</Artifactid><version>1.4.7</ version> </dependency> <dependency> < Groupid>javax.activation</groupid> <artifactid>activation</artifactid> <version>1.1.1</version> </ Dependency></DEPENDENCIES>      
Create a database table

Next, use MySQL to create a simple user table:

CREATE table' User ' (id int (11) primary key auto_increment comment  ' User ID ', username varchar ( Span class= "Hljs-number" >255) not null comment  ' username ', email varchar (255) not null comment  user mailbox ', Password varchar (255) not null comment 1) not null default 0 comment  ' user activation state: 0 means inactive, 1 is active ', Code varchar (255) not null comment  Activation code ') 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:

    1. Users fill in the relevant information, click the registration button
    2. The system first saves the user record to the database, where the user state is not activated
    3. The system sends an e-mail message and notifies the user to verify
    4. The user logs into the mailbox and clicks the Activate link
    5. 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:

PS: Complete code please see the following link, here only the main ideas

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) {Here you can verify that the fields are emptyUse regular expressions (which can be improved) to verify that a mailbox is formatted with a mailboxif (!email.matches ( "^\\[email protected" (\\w+\\.) +\\w+$ ")) {return FALSE;} //Generate activation Code string code=codeutil.generateuniquecode (); User User=new User (Username,email,password,0,code); //Save the user to the database Userdao userdao=new Userdaoimpl (); //save succeeded by thread to send a message to the user 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-configName="MySQL" ><PropertyName="Driverclass" >com.mysql.jdbc.driver</Property><PropertyName="Jdbcurl" >jdbc:mysql://127.0.0.1:3306/test1?usessl=false</Property><PropertyName="User" >root</Property><PropertyName="Password" >123456</Property><!--initialization When a connection pool tries to get the number of connections, the default is 3, the size should be between maxpoolsize and Minpoolsize--<PropertyName="Initialpoolsize" >5</Property><!--maximum idle time (in seconds) for a connection, 0 means that the connection is not obsolete--<property name= "MaxIdleTime" >30< Span class= "Hljs-tag" ></property> <!--the maximum number of connections at any given time, The default value is----<property name= "maxpoolsize" >20</property> <!--the minimum number of connections at any given time, the default value is 3--and <property name= "minpoolsize" >5</ property> </named-config></c3p0-config>        

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

<pre>
public class Dbutil {
private static Combopooleddatasource Cpds=null;

static{cpds=New Combopooleddatasource ("MySQL");PublicStatic ConnectionGetconnection() {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 ();}}           

}
</pre>

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 a 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:

    PublicClassMailutilImplementsRunnable {Private String Email;Recipient mailboxPrivate String Code;Activation CodePublicMailutil(string email, string code) {This.email = email;This.code = code; }PublicvoidRun() {1. Create a Connection object javax.mail.Session2. Create a Mail object javax.mail.Message3. Send an activation message String from ="[Email protected]";Sender e-mail String host ="Smtp.qq.com";Specify the host to send mail smtp.qq.com (QQ) |smtp.163.com (NetEase) Properties Properties = System.getproperties ();Gets the System Properties Properties.setproperty ("Mail.smtp.host", host);Set up mail server Properties.setproperty ("Mail.smtp.auth","true");Turn on authenticationtry {QQ Mailbox needs the following code, 163 mailboxes do 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 passwordauthenticationGetpasswordauthentication() {ReturnNew Passwordauthentication ("[Email protected]","XXX");Sender's email account, Authorization Code}});2. Create a 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 Email subject message.setsubject ("account Activation"); //2.4 Set the message contents String content = "" "Text/html;charset=utf-8"); //3. Send mail transport.send (message); System.out.println ("Mail successfully sent!");} catch (Exception e) {e.printstacktrace ();           }}}

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.

Code

Sndragon
Links: https://www.jianshu.com/p/8f8d7a46888f
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.

Email certification Process

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.