Web tutorial email sending and verification code

Posted by VTS on Sat, 02 Nov 2019 04:37:19 +0100

Article directory

I. use QQ email to send mail

1. Get the authorization code of QQ email

QQ email – > settings – > account – > generate authorization code


2. Import jar package mail.jar

Add to build path WEB-INF/lib
Right click – > build path – > add to build path

3. Test code

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailLearn {

	public static void main(String[] args) throws Exception {
		//Setting parameters
		Properties prop = new Properties();
	    prop.setProperty("mail.smtp.host", "smtp.qq.com");
	    prop.setProperty("mail.transport.protocol", "smtp");
	    prop.setProperty("mail.smtp.auth", "true");     //Do you want to validate users
	    prop.setProperty("mail.smtp.port", "465");
	    prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	    prop.setProperty("mail.smtp.socketFactory.port", "465");
	    
	    //5 steps to send mail
        //1. Get session
        Session session=Session.getInstance(prop);
        session.setDebug(true);
        //2. Create ts object
        Transport ts=session.getTransport();
        //3. Connect to the sending server
        //To connect to QQ mailbox server through a third party, you need email address and authorization code
        ts.connect("smtp.qq.com", "123123@qq.com", "avpvwswhgufvbdhh");
        //4. Create mail object
        Message message=createMessage(session);
        //5. Send email
        ts.sendMessage(message,message.getAllRecipients());
        ts.close();
	}
	
	//Create mail
	public static MimeMessage createMessage(Session session) throws Exception{
		//Create mail object
		MimeMessage message=new MimeMessage(session);
		//Claim sender
		message.setFrom(new InternetAddress("123123@qq.com"));
		//Declaration recipient
		message.setRecipient(Message.RecipientType.TO, new InternetAddress("123123@qq.com"));
		//Declaration theme
		message.setSubject("Mailbox send test");
		//Statement content
		message.setContent("<a href='http://Www.baidu. Com '> Baidu once < / a > "," text / HTML; charset = UTF-8 ");
		return message;
	}
}

Verification code implementation

1. Principle of picture verification code

When logging in, there is an img tag on the landing page. Fill in the address to obtain the verification code in the src path. The verification code is generated by the background. After receiving the request from the background, the president will generate random numbers and characters, place the randomly generated string into session, wait for verification, then call the verification code generation tool class to generate the verification code and return to the front desk.
The verification code entered in the foreground is compared with the verification code in the session, and the comparison is passed.

2. Verification code tool class

A little long, slightly (see source code)

3.VerifyCodeServlet

package org.lanqiao.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.util.VerifyCodeUtils;

/**
 * servlet generating verification code
 */
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public VerifyCodeServlet() {
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Cancel browser cache
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setContentType("image/jpeg");    //Set context type picture response
		//Get random characters and numbers
		String code=VerifyCodeUtils.generateVerifyCode(4);
		request.getSession().setAttribute("code", code);
		//Generate verification code by character
		VerifyCodeUtils.outputImage(100, 43, response.getOutputStream(), code);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

4.UserServlet.java

package org.lanqiao.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.bean.User;
import org.lanqiao.service.IUserService;
import org.lanqiao.service.impl.UserServiceImpl;

import jdk.nashorn.internal.ir.RuntimeNode.Request;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	//Declare and create UserService
	IUserService userService=new UserServiceImpl();

	//All requests will enter the service method
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Set character set encoding
		request.setCharacterEncoding("utf-8");
		//Receive the flag and judge the operation to be performed
		String flag=request.getParameter("flag");
		
		if("checkCode".equals(flag)) {
			//Perform verification code verification
			checkCode(request,response);
		}
	}
	
	//Verification code verification
	public void checkCode(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		//Get the verification code entered by the user
		String userCode=request.getParameter("userCode");
		//Take out the verification code in the session
		String code=(String)request.getSession().getAttribute("code");
		//Create pw object
		PrintWriter pw=response.getWriter();
		//Compare the two, if the input is correct and the verification is successful
		if(code.equalsIgnoreCase(userCode)) {			//Verification codes are case insensitive comparisons
			pw.write("200");
		}else {
			pw.write("400");
		}		
	}
}

5.login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Sign in</title>  
    <link rel="stylesheet" href="css/pintuer.css">
    <link rel="stylesheet" href="css/admin.css">
    <script src="js/jquery.js"></script>
    <script src="js/pintuer.js"></script>  
</head>
<body>
<div class="bg"></div>
<div class="container">
    <div class="line bouncein">
        <div class="xs6 xm4 xs3-move xm4-move">
            <div style="height:150px;"></div>
            <div class="media media-y margin-big-bottom">           
            </div>         
            <form action="UserServlet" method="post">
            <input type="hidden" name="flag" value="login"/>
            <div class="panel loginbox">
                <div class="text-center margin-big padding-big-top"><h1>Background management center</h1></div>
                <div class="panel-body" style="padding:30px; padding-bottom:10px; padding-top:10px;">
                    <div class="form-group">
                        <div class="field field-icon-right">
                            <input type="text" class="input input-big" name="username" placeholder="Login account" data-validate="required:Please fill in the account number" />
                            <span class="icon icon-user margin-small"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="field field-icon-right">
                            <input type="password" class="input input-big" name="pass" placeholder="Login password" data-validate="required:Please fill in the password" />
                            <span class="icon icon-key margin-small"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="field">
                            <input type="text" class="input input-big" name="code" placeholder="Fill in the verification code on the right" data-validate="required:Please fill in the verification code on the right" onblur="checkCode(this)" />
                        < img src="VerifyCodeServlet" alt="" width="100" height="32" class="passcode" style="height:43px;cursor:pointer;" onclick="this.src=this.src+'?'"    //Add here '"'"
                                                   
                        </div
                    </div>
                </div>
                <div style="padding:30px;"><input type="submit" class="button button-block bg-main text-big input-big" value="Sign in"></div>
            </div>
            </form>          
        </div>
    </div>
</div>
</body>
<script type="text/javascript">
	function checkCode(data){
		var data=$(data).val();
		$.ajax({
			url:"UserServlet",
			method:"get",
			data:{
				userCode:data,		//User entered verification code
				flag:"checkCode"
			},
			success:function(result){
				if(result=="200"){
					alert('Verification code input is correct');
				}else if(result="400"){
					alert('Verification code input error')
				}else{
					alert("unknown error")
				}
			}
		})
	}
</script>
</html>

Topics: Session Java JSP SSL