javaweb实现邮箱接收验证码
本篇介绍:web端通过java实现邮箱发送验证码
引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency>
package com.ycg.tab.utils;
import com.ycg.tab.common.Global; import lombok.extern.slf4j.Slf4j;
import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties;
/**
-
邮箱发送验证码服务 @author xjm @version 2020-07-06 */ @Slf4j public class MailUtils { /** 邮箱发送验证码服务 @param phonePersonMail 收件人邮箱地址 @param templateParam 验证码 @return */ public static String smsSendEmailCode(String phonePersonMail, String templateParam) { String companyEmail = Global.getConfig(“companyEmail”) != null ? Global.getConfig(“companyEmail”) : “yunlingkl”; // 企业邮箱 String companyEmailServer = Global.getConfig(“companyEmailServer”) != null ? Global.getConfig(“companyEmailServer”) : “smtp.126.com”; //邮箱SMTP服务器地址 String companyName = Global.getConfig(“companyName”) != null ? Global.getConfig(“companyName”) : “云领”; // 企业单位名称 String emailAuthCode = Global.getConfig(“emailAuthCode”) != null ? Global.getConfig(“emailAuthCode”) : “NJUQUCXNKMYBBZCW”;// 邮箱授权码 String result = “”; // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty(“mail.smtp.host”, companyEmailServer); properties.put(“mail.smtp.auth”, “true”); //阿里云服务器禁用25端口,所以服务器上改为465端口 properties.put(“mail.smtp.socketFactory.port”, “465”); properties.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”); properties.setProperty(“mail.smtp.socketFactory.fallback”, “false”); properties.setProperty(“mail.smtp.socketFactory.port”, “465”); // 获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(companyEmail, emailAuthCode); //发件人邮件用户名、授权码 } }); try { // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set Subject: 头部字段–标题 message.setSubject("【"+companyName+"】平台找回密码服务"); // Set From: 头部字段–发件人邮箱 message.setFrom(new InternetAddress(companyEmail+"@126.com")); // Set To: 头部字段–收件人邮箱 message.addRecipient(Message.RecipientType.TO, new InternetAddress(phonePersonMail)); message.setText("尊敬的用户:
" + "您好!感谢您使用【"+companyName+"】平台找回密码服务,您正在进行邮箱验证,本次请求的验证码为: " + templateParam + "(为了保障您账号的安全性,请在5分钟内完成验证)
" + "
" + "
" + companyName+"账号团队
" + DateUtils.dateFormat(new Date(), DateUtils.DATE_PATTERN));//设置发送内容 // 发送消息 Transport.send(message); result ="成功"; } catch (MessagingException mex) { mex.printStackTrace(); } return result; }
}
本篇文章暂且介绍到这里,具体实现根据业务来实现这里仅提供工具类
感谢支持!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
上一篇:
IDEA上Java项目控制台中文乱码