java邮箱发送验证码
目前项目中需要同时支持短信和邮箱验证,短信用的是腾讯云就不多说了,在此分享一下邮箱验证码发送。
首先,作为发送邮箱,需要开启POP3/SMTP/IMAP,登录邮箱–设置–账户–开启POP3/SMTP/IMAP,开启时可能会有短信验证,开启后显示验证码之类的一串英文,复制保存起来,后面要用

开启之后就可以作为发送邮箱,发验证码给用户了,代码如下
pom包引入:
<!--邮箱发送-->
<dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version>
</dependency>
邮箱发送工具类:
package com.es.biz.common.utils;import com.sun.mail.util.MailSSLSocketFactory;import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;/*** 邮箱发送工具类*/
public class MailUtils {public static void main(String[] args) {sendMail("邮件接收者");}/*** 发送验证码** @param receiveMail* @throws Exception*/public static void sendMail(String receiveMail) {Properties prop = new Properties();// 开启debug调试,以便在控制台查看prop.setProperty("mail.debug", "true");// 设置邮件服务器主机名prop.setProperty("mail.host", "smtp.163.com");// 发送服务器需要身份验证prop.setProperty("mail.smtp.auth", "true");// 发送邮件协议名称prop.setProperty("mail.transport.protocol", "smtp");// 开启SSL加密,否则会失败try {MailSSLSocketFactory sf = new MailSSLSocketFactory();sf.setTrustAllHosts(true);prop.put("mail.smtp.ssl.enable", "true");prop.put("mail.smtp.ssl.socketFactory", sf);// 创建sessionSession session = Session.getInstance(prop);// 通过session得到transport对象Transport ts = session.getTransport();// 连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com,qq使用:smtp.qq.comts.connect("smtp.163.com", "邮件发出者", "上面保存的验证码(一串英文)");// 创建邮件Message message = createSimpleMail(session, receiveMail);// 发送邮件ts.sendMessage(message, message.getAllRecipients());ts.close();} catch (Exception e) {e.printStackTrace();}}/*** @Method: createSimpleMail* @Description: 创建一封只包含文本的邮件*/public static MimeMessage createSimpleMail(Session session, String receiveMail) 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"};StringBuilder stringBuilder = new StringBuilder();for (int i = 0; i < 6; i++) {stringBuilder.append(letters[(int) Math.floor(Math.random() * letters.length)]);}//获取6位随机验证码(中文),根据项目需要选择中英文String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);// 创建邮件对象MimeMessage message = new MimeMessage(session);// 指明邮件的发件人message.setFrom(new InternetAddress("邮件发出者"));// 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveMail));// 邮件的标题message.setSubject("验证码");// 邮件的文本内容message.setContent("您的验证码:" + verifyCode + ",如非本人操作,请忽略!请勿回复此邮箱", "text/html;charset=UTF-8");// 返回创建好的邮件对象return message;}
}
















