java - 发送邮箱验证码 实战
话不多说上代码
注意:在发送邮件的邮箱后台需要申请开通邮箱授权服务,然后获取到 KEY
示例代码
public static void main(String[] args) {
// 邮箱
String maillAccount = "212121@qq.com";
// 验证码
String code = "1234";
String host = "smtp.gmail.com";
// 发送方邮箱地址
String url = "ceshi@gmail.com";
// 申请的KEY
String key = "qwrdfssdfsdfsf";
senfMaill(maillAccount,code,host,url,key);
}
编辑邮件提示信息
/**
* 创建邮件消息
*
* @param session 会话
* @param sendMail 发件人邮箱
* @param receiveMail 收件人邮箱
* @param code 验证码
* @return
* @throws Exception
*/
public static MimeMessage createMessage(Session session, String sendMail, String receiveMail, String code) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sendMail, "MIPAY", "UTF-8"));
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));
message.setSubject("邮箱验证码", "UTF-8");
message.setContent("<br><br>" +
" <font size =\"2\" face=\"arial\" >Dear " + receiveMail + "</font><br>" +
" <font size =\"2\" face=\"arial\" >您的密付邮箱验证码:" + code + ", 有效期5分钟。请勿向任何人泄露验证码,如果您并没有申请验证码,请立刻通知客服pywise@happypay.com</font><br>" +
" <font size =\"2\" face=\"arial\" >Thank you for your kind attention!</font><br><br>", "text/html;charset=UTF-8");
message.setSentDate(new Date());
message.saveChanges();
return message;
}
发送请求
public static boolean senfMaill(String maillAccount,String code, String host,String url,String key){
// 参数配置
Properties props = new Properties();
// 使用的协议
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", host);
// 需要请求认证
props.setProperty("mail.smtp.auth", "true");
//设置SSL传输端口
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.connectiontimeout", "60000");
//根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getInstance(props);
// 设置为debug模式, 可以查看详细的发送log
session.setDebug(true);
// 邮件消息体
MimeMessage message = null;
try {
LOG.info("登录验证码:{}", code);
//消息体
message = createMessage(session, url, maillAccount, code);
Transport transport = session.getTransport();
transport.connect(url, key);
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
//关闭连接
transport.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}