注册成功邮箱发送邮件并激活
发邮件的工具类
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 { public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException { // 1.创建一个程序与邮件服务器会话对象 Session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP"); props.setProperty("mail.host", "smtp.126.com"); props.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("hysteria_7", "hysteria7");//发送者邮箱 发送者授权码 一般为公司的公共邮箱 } }; Session session = Session.getInstance(props, auth); // 2.创建一个Message,它相当于是邮件内容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("hysteria_7@126.com")); // 设置发送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者 message.setSubject("用户激活"); // message.setText("这是一封激活邮件,请<a href='#'>点击</a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.创建 Transport用于将邮件发送 Transport.send(message); } }
需要用到的jar
mail.jar
使用:
//发送邮件 String emailMsg = "恭喜您注册成功,请点击下面的链接进行激活账户" + "<a href='http://localhost:8080/YShop/active?activeCode="+ activeCode +"'>" + "http://localhost:8080/YShop/active?activeCode="+ activeCode +"</a>"; try { MailUtils.sendMail(user.getEmail(), emailMsg); } catch (MessagingException e) { e.printStackTrace(); }
//activeCode 为用户注册时后台自动赋值的一个UUID 为了点击激活时做匹配用
//private String code;//激活码
String activeCode = CommonUtil.getUUID();
user.setCode(activeCode);
紫色的地址可以写成公网的IP 这样外网上也可以激活(测试是在本地)
效果:
UUID

激活代码:
//1.获得激活码 Servlet层: String activeCode = request.getParameter("activeCode"); UserService service = new UserService(); service.active(activeCode); service层 UserDao dao = new UserDao(); try { dao.active(activeCode); } catch (SQLException e) { e.printStackTrace(); } dao层 QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "update user set state=? where code=?"; runner.update(sql, 1,activeCode);//设置激活状态为1

浙公网安备 33010602011771号