欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSH邮箱注册**实现

程序员文章站 2022-03-18 09:33:13
...

首先jar包是mail.jar,百度找就ok了。
准备两个邮箱,建议阿里云邮箱接收,163邮箱发送,qq邮箱会出现接收很慢的情况。

效果图

SSH邮箱注册**实现

工具类

MailUtils.java

package com.zsj.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

	//发邮箱,给谁发email,邮箱标题,以及email的内容
	//163邮箱发给阿里云邮箱
	public static void sendMail(String email, String title, String emailMsg)
			throws AddressException, MessagingException {
		

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");

		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				//账号 和 授权码
				return new PasswordAuthentication("17856007510", "OXJDIIMDAPUGXYCX");
			}
		};

		Session session = Session.getInstance(props, auth);

		Message message = new MimeMessage(session);
		//改
		message.setFrom(new InternetAddress("aaa@qq.com")); 

		message.setRecipient(RecipientType.TO, new InternetAddress(email)); 

		//设置标题
		message.setSubject(title);

		message.setContent(emailMsg, "text/html;charset=utf-8");

		

		Transport.send(message);
	}
}


工具类中的授权码,在163邮箱中设置可以找到
SSH邮箱注册**实现
SSH邮箱注册**实现
点击开启,按照提示就能得到授权码,如果已经是开启的,就关闭再开启。

代码

这里code是用户标识,把id和用户名传递相当于泄露,所以设置code码。
UserAction.java

public String register() throws Exception {
		
		//表单并没有把所有数据封装,这时需要我们手动去封装
		user.setState(0);
		user.setCode(UUID.randomUUID().toString());
		user.setIamge("0");
		user.setLevel(1);
		user.setCoin(1000);
		
		userService.addUser(user);
		
		//把id和用户名传递相当于泄露,所以设置code码
		MailUtils.sendMail(user.getEmail(), "用户**", "恭喜你注册成功,请点击下面的链接进行**吧!<a href='http://localhost:8080/SSH_Forum/UserAction_active?userCode="+user.getCode()+"'>点击这里</a>");
		
		return "toRegisterSuccess";
		
		
	}
	
	//用户邮箱**
	public String active() throws Exception {
		//System.out.println("active");
		userService.activeUser(userCode);
		return "toLogin";
	}

UserService.java

//**用户
	public void activeUser(String userCode) {
		userDao.activeUser(userCode);
	}

UserDao.java

public void activeUser(String userCode) {
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		String sql = "update user set state = 1 where code = ?";
		NativeQuery query = session.createSQLQuery(sql);
		query.setParameter(1, userCode);
		query.executeUpdate();
	}
相关标签: SSH smtp