日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java邮箱实现忘记修改密码

發布時間:2023/12/20 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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邮箱实现忘记修改密码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。