Java邮箱验证码注册

注册

使用邮箱验证码实现用户注册早已不在是什么新鲜的事,但是对于我这些手(菜鸟)来说还是比较茫然的,所以我将我这第一次的经验总结分享出来,希望能够有助于茫然的你-----------》》》》

主要有一下步骤:

  1. 发送邮箱验证码的工具类;
  2. 发送验证码的servlet类;
  3. 用户注册的servlet类;
  4. 用户登录的jsp页面;
  5. 需要的jar包;
  6. 邮箱账户的设置。

然后让我们一步一步来看:

1. 发送邮箱验证码的工具类


import java.util.Random;

import org.apache.commons.mail.HtmlEmail;

public class SendEmailUtil {
	public int sendEmail(String emailaddress) {
		try {
			Random random = new Random();
			int code = random.nextInt(9000)+1000; 
			HtmlEmail email = new HtmlEmail();// 不用更改
			email.setHostName("smtp.qq.com");// 需要修改,126邮箱为smtp.126.com,163邮箱为163.smtp.com,QQ为smtp.qq.com
			email.setCharset("UTF-8");
			email.addTo(emailaddress);// 收件地址

			email.setFrom("发件人邮箱", "发件人用户名");// 此处填邮箱地址和用户名,用户名可以任意填写
			//hhhjkkkhhjklj(IMAP/SMTP服务)---这里需要改为你自己
			email.setAuthentication("发件人邮箱", "bzqaboqcccmyfdeb");// 此处填写邮箱地址和客户端授权码

			email.setSubject("邮件名称");// 此处填写邮件名,邮件名可任意填写
			email.setMsg("尊敬的用户您好,您本次注册的验证码是:" + code);// 此处填写邮件内容

			email.send();
			return code;
		} catch (Exception e) {
			return 0;
		}
	}

}

2. 发送验证码的servlet类–重写doGet方法

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//接收邮箱
		String email = request.getParameter("firstEmail");
		//用户传递响应结果
		String sendResult = "";
		if(email!=null && !"".equals(email)) {
			//发送邮箱验证码,并返回验证码
			SendEmailUtil seu = new SendEmailUtil();
			int code = seu.sendEmail(email);
			
			if(code != 0) {
				//封装邮箱和验证码
				request.getSession().setAttribute("code",code);
				request.getSession().setAttribute("firstEmail", email);
				
				sendResult = "ok";
			}else {
				sendResult = "发送验证码失败";
			}
		}else {
			sendResult = "请输入有效的邮箱地址";
		}
		//封装为json并对客户端响应
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(sendResult));
	}

3. 用户注册的servlet类–重写doGet方法

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取表单内容
		String name = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		String repwd = request.getParameter("rePwd");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		
		//获取session域的验证码和邮箱
		int code = (int) request.getSession().getAttribute("code");
		String firstEmail = (String) request.getSession().getAttribute("firstEmail");
		
		//获取用户输入验证码
		String vilidateCode = request.getParameter("eCode");
		int vCode = 0;
		if(vilidateCode!=null && !"".equals(vilidateCode)) {
			vCode = Integer.parseInt(vilidateCode);
		}
		
		//用于封装数据
		User user = new User();
		//返回结果
		String result = "";
		
		//如果两次密码一致则封装到实体类
		if(!repwd.equals(pwd)) {
			result = "两次密码不一致";
		}else{
			//如果两次邮箱不一致,响应结果
			if(!firstEmail.equals(email)) {
				result = "请使用接收验证码的邮箱注册";
			}else {
				//判断验证码
				if(vCode == code) {
					
					UserService userService = new UserServiceImpl();
					int row = 0;
					try {
						if((name!=null&&!"".equals(name))&&(pwd!=null&&!"".equals(pwd))&&(phone!=null&&!"".equals(phone))) {
							//都满足则封装数据并存储
							user.setUname(name);
							user.setUpwd(pwd);
							user.setUphone(phone);
							user.setUemail(email);
							row = userService.register(user);
						}
					} catch (Exception e) {
						//如果出现异常,重定向页面,由于没有数据传输,所以可以进行响应重定向
						response.sendRedirect("error.html");
					}
					if(row == 1) {
						//一切无误,返回ok
						result = "ok";
					}else {
						result = "请输入正确的个人信息";
					}
				}else {
					result = "验证码不正确";
				}
			}
		}
		//响应给客户
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(result));
	}

4. 用户登录的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>使用邮箱验证码实现注册</title>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
	<!--登录注册表-->
	<div>
		<form id="form">
			<div class="flrg-1">
				<h3>注册</h3>
				<div>
					<input type="text" class="in-1" placeholder="您的用户名"
						name="username" id="username" onblur="checkNotName()"> <br>
					<font color="red" id="usernameError"></font>
				</div>
				<div class="a">
					<input type="password" class="in-1" placeholder="输入密码" name="pwd"
						id="pwd" onblur="checkPwd()"> <br> <font
						color="red" id="pwdError"></font>
				</div>
				<div class="a">
					<input type="password" class="in-1" placeholder="再次确认密码"
						name="repwd" id="rePwd" onblur="checkRePwd()"> <br>
					<font color="red" id="rePwdError"></font>
				</div>
				<div class="a">
					<input type="text" class="in-1" placeholder="输入手机号码" name="phone"
						id="phone" onblur="checkPhone()"> <br> <font
						color="red" id="phoneError"></font>
				</div>
				<div class="a">
					<input type="email" class="in-1" placeholder="输入邮箱地址" name="email"
						id="email" onblur="checkEmail()"> <br> <font
						color="red" id="emailError"></font>
				</div>
				<div class="a">
					<input type="text" class="in-1" placeholder="邮箱验证码" name="eCode"
						id="eCode"> <br> <font color="red" id="eCodeError"></font>
				</div>
				<div class="a">
					<input type="button" id="send" value="发送邮箱验证码">
				</div>
				<div class="a">
					<input type="button" id="btn" style="text-align: center;"
						value="注册">
				</div>
				<script>
                $("#send").click(function(){
            		var email = $("#email").val();
            		var result = "ok";
            		$.ajax({
            			type:"post",
            			async:true,
            			url:"SendEmailVilidataCodeServlet",
            			data:"firstEmail="+email,
            			dataType:"json",
            			success:function(sendResult){
            				if(result==sendResult){
            					alert("已发送成功,注意查收");
            				}else{
            					$("#send").val("请重新发送");
            				}
            			},
            			error:function(){
            				alert("发送验证码失败");
            			}
            		})
            	});
               </script>
				<script>
	                $("#btn").click(function(){
	                	var username = $("#username").val();
	            		var pwd = $("#pwd").val();
	            		var rePwd = $("#rePwd").val();
	            		var phone = $("#phone").val();
	            		var eCode = $("#eCode").val();
	            		var email = $("#email").val();
	            		var result = "ok";
	            		$.ajax({
	            			type:"post",
	            			async:true,
	            			//最好使用绝对路径
	            			url:"${pageContext.request.contextPath}/RegisterServlet",
							data:"username="+username+"&pwd="+pwd+"&rePwd="+rePwd+"&eCode="+eCode+"&email="+email+"&phone="+phone,
	            			dataType:"json",
	            			success:function(resultFinal){
	            				if(result==resultFinal){
									alert(resultFinal);
									window.location.href="login.jsp";
								}else{
									$("#eCodeError").html(resultFinal);
								}
	            			},
	            			error:function(){
	            				alert("注册失败");
	            			}
	            		})
	            	});
               </script>
			</div>
		</form>
	</div>
</body>
</html>

注册界面其实随便写一个就可以了,主要还是工具类的使用方法,和整体结构的思想,下面工具类所需要的各种jar包

5. 需要的jar包

以上是工具类所需要的jar包
以上是工具类所需要的jar包

至此我们代码部分已经结束

6. 邮箱账户的设置。

在浏览器登录QQ邮箱就可以设置:
点击设置—>账户—>开启对应的功能(注意:记住授权码)
在这里插入图片描述
在这里插入图片描述
至此完成所有步骤,
最后,很感谢网上热心的朋友的文章和我的同桌。
如果有何异议,希望不吝分享。谢谢您的浏览!

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用 Java 实现邮箱验证码的示例代码: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class EmailVerification { public static void main(String[] args) throws MessagingException { String to = "recipient@example.com"; // 收件人邮箱地址 String from = "sender@example.com"; // 发件人邮箱地址 String host = "smtp.example.com"; // SMTP 服务器 // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 获取默认的 Session 对象 Session session = Session.getDefaultInstance(properties); // 创建一封邮件 MimeMessage message = new MimeMessage(session); // 设置发件人地址 message.setFrom(new InternetAddress(from)); // 设置收件人地址 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("邮箱验证码"); // 生成随机验证码 String code = generateCode(); // 设置邮件正文 message.setText("您的验证码是:" + code); // 发送邮件 Transport.send(message); } // 生成随机验证码 private static String generateCode() { int codeLength = 6; // 验证码长度 String code = ""; for (int i = 0; i < codeLength; i++) { code += (int) (Math.random() * 10); } return code; } } ``` 以上代码使用 JavaMail API 实现了发送一封带有随机验证码的电子邮件。你需要替换 `to`、`from` 和 `host` 变量的值为你自己的邮箱地址和 SMTP 服务器地址,然后就可以运行代码了。 需要注意的是,在发送邮件之前,你需要先引入 JavaMail API 库,并且需要认证你的邮箱账户信息。具体实现方式可以参考 JavaMail 官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值