java邮箱实现忘记修改密码
一、spring-boot-starter-mail发送邮件(发送邮箱需要开启服务)
1.添加依赖
<!-- 邮件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2.application.yml中配置
mail:test-connection: truehost: kkk.comport: 25username: 2222222.compassword: 22222default-encoding: utf-8protocol: smtpemailFrom: 2222222.com
3.自定义配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "spring.mail")
public class EmailConfig {private String emailFrom;public String getEmailFrom() {return emailFrom;}public void setEmailFrom(String emailFrom) {this.emailFrom = emailFrom;}}
3.service代码
package com.pcr.user.service;import javafx.util.Pair;import java.io.File;
import java.util.List;/*** @author zyn* @date now*/
public interface EmailService {/*** 发送简单邮件* @param to 收件人地址* @param subject 邮件标题* @param content 邮件内容*/public void sendSimpleMail(String[] to, String subject, String content);/*** 发送简单邮件* @param to 收件人地址* @param subject 邮件标题* @param content 邮件内容* @param attachments<文件名附件> 附件列表*/public void sendAttachmentsMail(String[] to, String subject, String content, List<Pair<String, File>> attachments);/*** 发送html格式邮件* @param subject 主题* @param content 内容*/public void sendHtmlMail(String to , String subject, String content);// /**
// * 发送模板邮件
// * @param to 收件人地址
// * @param subject 邮件标题
// * @param content<key内容> 邮件内容
// * @param attachments<文件名附件> 附件列表
// */
// public void sendTemplateMail(String[] to, String subject, Map<String, Object> content, List<Pair<String, File>> attachments);
}
package com.pcr.user.service.impl;import com.pcr.user.config.EmailConfig;
import com.pcr.user.service.EmailService;
import javafx.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;/*** @Author zyn* @Version 1.0.0* @Date 2020-02-15 21:31*/
@Service
public class EmailServiceImpl implements EmailService {@Autowiredprivate EmailConfig emailConfig;@Autowiredprivate JavaMailSender mailSender;/*** 用来发送模版邮件*/
// @Autowired
// private TemplateEngine templateEngine;@Overridepublic void sendSimpleMail(String[] to, String subject, String content) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(emailConfig.getEmailFrom());message.setTo(to);message.setSubject(subject);message.setText(content);mailSender.send(message);}@Overridepublic void sendAttachmentsMail(String[] to, String subject, String content, List<Pair<String, File>> attachments) {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = null;try {helper = new MimeMessageHelper(message, true);helper.setFrom(emailConfig.getEmailFrom());helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);if(attachments != null){for(Pair<String,File> attachment:attachments){FileSystemResource file = new FileSystemResource(attachment.getValue());helper.addAttachment(attachment.getKey(), file);}}mailSender.send(message);} catch (Exception e) {e.printStackTrace();}}@Overridepublic void sendHtmlMail(String to, String subject, String content) {MimeMessage message = mailSender.createMimeMessage();try {//true表示需要创建一个multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(emailConfig.getEmailFrom());helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);mailSender.send(message);System.out.println("html格式邮件发送成功");} catch (Exception e) {System.out.println("html格式邮件发送失败");}}// @Override
// public void sendTemplateMail(String[] to, String subject, Map<String, Object> content, List<Pair<String, File>> attachments) {
// Context context = new Context();
// context.setVariables(content);
// String emailContent = templateEngine.process("mail", context);
// sendAttachmentsMail(to,subject,emailContent,attachments);
// }
}
二、发送修改密码连接
1.连接需要加密和时效验证
http://192.168.9.6:8080/#/modifypwd?key=0e01fe12f88fcb38d97cc4a7e8fa9c921d6bb27b430bceac12579a8dbd6094e4
key中保存的是用户名+当前时间戳 用于验证用户和链接有效期时长
我采用的是Des加密解密
String context = "你好:<br/>您收到这封邮件是因为您申请了一个修改密码的请求。<br/>您可以点击如下链接设置您的密码,如果点击无效,请复制到浏览器中:<br/>"+link+"<br/>该链接十分钟内有效<br/>如果您有疑问,请给我们联系";if (StringUtils.isEmpty(user.getEmail())) {throw new Exception("邮箱不能为空");}if (!user1.getEmail().equals(user.getEmail())) {throw new Exception("此邮箱不是该用户的注册邮箱");}emailService.sendHtmlMail(user.getEmail(), "修改密码", context);
DES加密工具类
package com.pcr.commom.util;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Date;public class DESUtil {private final static String HEX = "0123456789abcdef";private static void appendHex(StringBuffer sb, byte b) {sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));}/*** 解密** @param raw key* @param encrypted 加密后的字节* @return 返回解密后的字节* @throws Exception*/private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] decrypted = cipher.doFinal(encrypted);return decrypted;}/*** 解密** @param seed key* @param encrypted 加密的字符* @return 返回解密的字符* @throws Exception*/public static String decrypt(String seed, String encrypted) throws Exception {byte[] rawKey = getRawKey(seed.getBytes());byte[] enc = toByte(encrypted);byte[] result = decrypt(rawKey, enc);return new String(result);}/*** 加密** @param raw key* @param clear* @return* @throws Exception*/private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(clear);return encrypted;}/*** 加密** @param seed key* @param cleartext 需要加密的字符串* @return 返回加密的字符* @throws Exception*/public static String encrypt(String seed, String cleartext) throws Exception {byte[] rawKey = getRawKey(seed.getBytes());byte[] result = encrypt(rawKey, cleartext.getBytes());return toHex(result);}public static String fromHex(String hex) {return new String(toByte(hex));}/*** key 加密** @param seed* @return* @throws Exception*/private static byte[] getRawKey(byte[] seed) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("DES");SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");sr.setSeed(seed);kgen.init(56, sr); // des 的密钥为56位SecretKey skey = kgen.generateKey();byte[] raw = skey.getEncoded();return raw;}/*** to byte** @param hexString* @return*/public static byte[] toByte(String hexString) {int len = hexString.length() / 2;byte[] result = new byte[len];for (int i = 0; i < len; i++)result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();return result;}/*** 转为为16进制** @param buf 需要转化的byte* @return 返回转化后的字符串*/public static String toHex(byte[] buf) {if (buf == null)return "";StringBuffer result = new StringBuffer(2 * buf.length);for (int i = 0; i < buf.length; i++) {appendHex(result, buf[i]);}return result.toString();}/*** 转为为16进制** @param buf 需要转化的byte* @return 返回转化后的字符串*/public static String toHex(String txt) {return toHex(txt.getBytes());}public static void main(String[] args) throws Exception {String seed = "LOVEMOIVE"; // des加密时使用的keyDate date = new Date(); // 获取当前时间long time = date.getTime();String plainText = "" + time + "@" + "1432531621@qq.com"; // 组装时间和用户邮箱String c = DESUtil.encrypt(seed, plainText); // 加密参数String link = "http://localhost:8080/LoveMovie/forgetPassword/resetPassword?key=" + c;System.out.println("-----------解密后的链接为---------------------");System.out.println(link);//----------在用户登录邮箱访问重置密码链接后对链接的参数进行解密------String p = DESUtil.decrypt(seed, c);System.out.println("-----------解密后的key参数---------------------");System.out.println(p);}/*output:-----------解密后的链接为---------------------http://localhost:8080/LoveMovie/forgetPassword/resetPassword?key=86bfd878ab98b8dcc16f07f29b212a6bf5221568a680766ac900978672e6fdfc-----------解密后的key参数---------------------1561115711489@1432531621@qq.com*/}
2.解密验证
String p = DESUtil.decrypt(key, userVo.getKey());int i = p.indexOf("@");String timestamp = p.substring(0, i);String username = p.substring(i + 1);if (!StringUtils.isNotBlank(timestamp)) {throw new Exception("解密失败");}if (!StringUtils.isNotBlank(username)) {throw new Exception("解密失败");}long time = Long.parseLong(timestamp);long difference = (System.currentTimeMillis()-time)/1000/60;long min = 10L;if (difference > min) {throw new Exception("链接超过十分钟已失效");}if (!userVo.getUserName().equals(username)) {throw new Exception("请填写正确的用户");}
java邮箱实现忘记修改密码相关推荐
- java编写脚本校验修改密码_java编写一个更改密码校验程序,有两个密码框,一个用于输入新密码,另一个请输入确认密码……...
展开全部 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JBu ...
- java用for循环修改密码_Java for循环的几种用法分析
J2SE 1.5提供了另一种形式的for循环.借助这种形式的for循环,可以用更简单地方式来遍历数组和Collection等类型的对象.本文介绍使用这种循环的具体方式,说明如何自行定义能被这样遍历的类 ...
- java窗口怎么实现修改密码_【求助】Java中如何实现更改windows密码
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 import java.io.File; import java.io.FileWriter; import java.io.IOException; i ...
- react-hooks + node 使用qq邮箱发送验证码,验证修改密码
在平常,我们写登录注册react项目时,我们可能会考虑使用QQ邮箱发送验证码登录注册,或者使用QQ邮箱验证来修改密码,下面,我们就来使用QQ邮箱来简单发送个邮件. 1.当我们想在react项目中使用Q ...
- 麒麟linux修改密码,麒麟堡垒机密码定期修改手册
1.堡垒机设置部分 自动修改密码可以为Windows系统.Linux系统.Unix系统进行密码托管,并且按运维相关要求进行口令强度和周期的修改. 堡垒机上设置一台设备自动修改密码按如下步骤: (1)设 ...
- deepin和ubuntu中mysql8.0.16修改密码蜜汁问题
下面只是修改密码的记录 # # # # # # # # # # # # # # # # 首次修改密码# # # # # # # # # # # # # # # # 关闭正在运行的 MySQL : # ...
- java修改密码代码_java web实现 忘记密码(找回密码)功能及代码
java web实现 忘记密码(找回密码)功能及代码 (一).总体思路 (二).部分截图 (三).部分代码 (一).总体思路: 1.在 找回密码页面 录入 姓名.邮箱和验证码,录入后点击[提交]按钮, ...
- 企业邮箱怎么注册账号?忘记邮箱密码怎么修改密码?
企业邮箱怎么注册账号?一个专业体面的邮箱,可以帮助你在收件人心中树立一个不错的个人品牌形象,比如TOM企业邮箱:而你的邮件也因此受到更多的关注,客户沟通上也更加通畅.随着即时通讯的发展,像微信.QQ以 ...
- java 邮箱找回密码_【JavaWeb】通过邮件找回密码
前言 本文将介绍忘记密码时通过发送重置密码邮件找回密码的实现思路.整个实现过程中最重要的就是以下三点: 如何发送邮件到用户指定邮箱 邮件中的重置密码链接构成是怎么样的 验证重置密码链接的合法性(是否过 ...
- java邮箱找回密码_java实现邮箱找回密码 简单邮件
首先 发件人的POP/SMTP服务要打开 发件人的密码为服务的授权码 js方法 //找回密码 function send(){ var lostemail = $("#lostemail ...
最新文章
- Tensorflow警告:our CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
- sqlite3数据存储最多存储多少条数据?达到上限如何处理?_在数据爆炸的当下,教你设计一个能实现9个9数据可靠性的存储系统...
- 前缀函数及kmp算法
- a king读后感 love of the_读后感kinglear
- ‘a’、“a”、‘abc’和“abc”的区别
- PHP基础班初学感悟
- Linux命令----cat
- mysql 字符串截取_MySQL|SUBSTR() 函数用法
- 初中物理凸透镜成像动态图_人教版初中物理八年级上册 平面镜成像 公开课优质课课件教案视频...
- 计算机中丢失profapi,profapi.dll
- idea2017显示maven Project菜单
- 拓端tecdat|Matlab正态分布、历史模拟法、加权移动平均线 EWMA估计风险价值VaR和回测Backtest标准普尔指数 SP500时间序列
- 十二月份找工作好找吗_人民大学在职研究生将来好找工作吗?
- 两台电脑共享鼠标键盘Synergy
- R语言迹检验协整关系式_【R语言】单位根检验、协整检验和格兰杰因果关系检验三者之间的关系...
- 大数据第一季--Hadoop(day7)-徐培成-专题视频课程
- Python文件名繁体转简体
- healthd log 解读
- MySQL中试图的应用
- [享学Eureka] 二十二、DiscoveryClient服务注册的小工具:InstanceInfoReplicator
热门文章
- 上海地铁二号线和一号线的差距
- 顺丰快递单号查询API开发指南-快递鸟
- windows下red5配置
- 固定不动的层(兼容IE6)
- 利用ansys计算机械结构最小安全系数教程,安全系数
- flashpaper java_基于FlashPaper实现JSP在线阅读代码示例
- android吉他谱组件,Paranoid Android drum吉他谱
- Bean初始化错误:Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
- 计算机亮度快捷键,调节电脑亮度的快捷键是什么
- 基于java的健身房管理系统的设计与实现