Java实现邮箱验证码
前言
相比于java实现短信验证码,邮箱验证码就简单了许多,目前只是简单的利用java发送自定义内容至指定邮箱,等过几天再弄短信和邮箱验证码Web版本的。查询网上资料,得知相比于网易邮箱,QQ邮箱是最麻烦的,而且平时我个人使用的也是QQ邮箱,所以也是选择了QQ邮箱。
配置协议
1.首先,我们需要打开发送方的QQ邮箱,也就是你的邮箱,点击上方的设置。
进入之后,点击账户,下滑至POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,将POP3/SMTP服务打开即可
开启服务之后,会获得一个授权码,把它记下来,后面写代码的时候会用的到。
代码实现(黄色部分需修改为自己数据)
Mail_Java.java:
package util; 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; import com.sun.mail.util.MailSSLSocketFactory; /** * JavaMail发送邮件: java版本-与web无关 * 前提是QQ邮箱里帐号设置要开启POP3/SMTP协议 * * */ public class Mail_java { public static void main(String[] args) throws Exception { Properties prop = new Properties(); // 开启debug调试,以便在控制台查看 prop.setProperty("mail.debug", "true"); // 设置邮件服务器主机名 prop.setProperty("mail.host", "smtp.qq.com"); // 发送服务器需要身份验证 prop.setProperty("mail.smtp.auth", "true"); // 发送邮件协议名称 prop.setProperty("mail.transport.protocol", "smtp"); // 开启SSL加密,否则会失败 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); // 创建session Session session = Session.getInstance(prop); // 通过session得到transport对象 Transport ts = session.getTransport(); // 连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com ts.connect("smtp.qq.com", "发送方的QQ号", "POP3/SMTP协议授权码"); // 创建邮件 Message message = createSimpleMail(session); // 发送邮件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); } /** * @Method: createSimpleMail * @Description: 创建一封只包含文本的邮件 */ public static MimeMessage createSimpleMail(Session session) throws Exception { // 获取6为随机验证码 String[] letters = new String[] { "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m", "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M", "0","1","2","3","4","5","6","7","8","9"}; String stringBuilder =""; for (int i = 0; i < 6; i++) { stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)]; } // 创建邮件对象 MimeMessage message = new MimeMessage(session); // 指明邮件的发件人 message.setFrom(new InternetAddress("发送方QQ@qq.com")); // 指明邮件的收件人,发件人和收件人如果是一样的,那就是自己给自己发 message.setRecipient(Message.RecipientType.TO, new InternetAddress("接受方QQ@qq.com")); // 邮件的标题 message.setSubject("JavaMail测试"); // 邮件的文本内容 message.setContent("欢迎您注册【OG高玩会】,账号注册验证码为(一分钟有效):"+stringBuilder+",请勿回复此邮箱", "text/html;charset=UTF-8"); // 返回创建好的邮件对象 return message; } }
所需jar包
链接:https://pan.baidu.com/s/14PvQvB4hUBUrrk-uTus_6w
提取码:xeg3