先去开启163邮箱的smtp服务然后就可以开始撸代码了
添加依赖
<!--发送邮件的jar包--><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>
EmailUtils类:
import com.sun.mail.util.MailSSLSocketFactory;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;public class EmailUtils implements Runnable {private String email;//收件人邮箱private String code;//验证码public EmailUtils(String email,String code) {this.email = email;this.code=code;}public void run() {// 1.创建连接对象javax.mail.Session// 2.创建邮件对象 javax.mail.Message// 3.发送一封激活邮件String from = "xxx@";// 发件人电子邮箱String host = ""; // 指定发送邮件的主机(QQ)|(网易)Properties properties = System.getProperties();// 获取系统属性properties.put("mail.host","" );//设置主机名properties.put("mail.transport.protocol", "smtp");//发送邮件协议名称properties.put("mail.smtp.auth", true);//是否认证// properties.setProperty("mail.smtp.host", host);// 设置邮件服务器// properties.setProperty("mail.smtp.auth", "true");// 打开认证try {// MailSSLSocketFactory sf = null;// 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("xxx@", "OTJMBKRBASWVHVLW"); // 发件人邮箱账号、授权码}});// 2.创建邮件对象Message message = new MimeMessage(session);// 2.1设置发件人message.setFrom(new InternetAddress(from));// 2.2设置接收人message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));// 2.3设置邮件主题message.setSubject("Penguin账号注册");// 2.4设置邮件内容String content = "<html><head></head><body><h3>欢迎使用Penguin,您的验证码为:</h3><br/><h3>"+code+"</h3>" +"<br/><h3>请您在10分钟内使用此验证码完成注册,过期将会失效。</h3>" +"<br/><h3>如有疑问可拨打客服电话:xxxxxx</h3><br/><h3>请勿回复此邮件,感谢您的合作</h3></body></html>";message.setContent(content, "text/html;charset=UTF-8");// 3.发送邮件Transport.send(message);System.out.println("邮件成功发送!");} catch (Exception e) {e.printStackTrace();}}}
写项目的时候封装了Json和Redis的工具类:JsonData和RedisClient
@RestController@RequestMapping(value = "/penguin")public class VerifyEmailController {@Autowiredprivate RedisClient redisClient;@NoneAuth@RequestMapping(value = "/mailsend")public Object sendMail(String email) throws IOException {//生成6位验证码Random random = new Random();StringBuilder code= new StringBuilder();for (int i=0;i<6;i++){code.append(random.nextInt(10));}//开启一个新的线程发送邮件new Thread(new EmailUtils(email, code.toString())).start();redisClient.set(email,code.toString(),600000);return JsonData.buildSuccess();}}
记录一下,怕一扭头就忘了。真实。
如果觉得《JavaWeb项目实现163邮箱验证码》对你有帮助,请点赞、收藏,并留下你的观点哦!