邮箱激活,验证码的实现
-
我用的是qq邮箱往163邮箱发送的。因此需要登录QQ邮箱,在设置->账户面板中开启POP3/SMTP服务。并且从这里获得授权码,
-
POM.xml 中导入mail
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
-
接下来直接建类完成邮箱的验证码发送
package com.yckj.springbootdemo.emaill; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * <p> * Title:com.yckj.springbootdemo.emaill * </p> * <p/> * <p> * Description: 描述【邮箱的验证码发送】 * </p> * <p/> * <p> * Copyright: Copyright (c) 2020 * </p> * <p/> * <p> * Company: 太原工业学院 * </p> * * @author WeiHuiQiang * @version 1.0 * @created 2020/3/16 15:14 */ public class SendMail { public static void main(String[] args) { sendMail("m13546356160@163.com"); } /** * * @param emaill 收件人邮箱 */ public static void sendMail(String emaill) { /*随机生成六位随机数验证码 */ StringBuffer stringBuffer=new StringBuffer(); for (int x=0;x<=5;x++) { int random = (int) (Math.random() * (10 - 1)); stringBuffer.append(random); } String code = stringBuffer.toString(); // 1.创建连接对象javax.mail.Session // 2.创建邮件对象 javax.mail.Message // 3.发送一封激活邮件 String from = "3593495446@qq.com";// 发件人电子邮箱 String sendEmaill = emaill; // 收件人电子邮箱 String host = "smtp.qq.com"; // 指定发送邮件的主机 smtp.qq.com(QQ)|smtp.163.com(网易) Properties properties = new Properties(); /* 与 Properties properties = System.getProperties() 相同,用来配置文件*/ properties.setProperty("mail.smtp.host", host); // 设置邮件服务器 properties.setProperty("mail.smtp.auth", "true"); // 打开认证 try { //QQ邮箱需要下面这段代码,163邮箱不需要 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); // 1.获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("3593495446@qq.com", "cxmkeuceyukrcifh"); // 发件人邮箱账号、授权码 } }); // 2.创建邮件对象 Message message = new MimeMessage(session); // 2.1设置发件人 message.setFrom(new InternetAddress(from)); /*new InternetAddress(xxx) 将字符串转化为地址*/ // 2.2设置接收人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendEmaill)); // 2.3设置邮件主题 message.setSubject("账号验证码"); // 2.4设置邮件内容 String content = "<html><head></head><body><h1>你的验证码是:</h1><h3>" + code +"</h3></body></html>"; message.setContent(content, "text/html;charset=UTF-8"); // 3.发送邮件 Transport.send(message); System.out.println("邮件成功发送!"); } catch (Exception e) { e.printStackTrace(); } } }