新增 邮件发送验证码模板

This commit is contained in:
萌狼蓝天 2024-10-09 16:17:48 +08:00
parent ab1419f594
commit 81eae9159e
3 changed files with 53 additions and 8 deletions

View File

@ -16,10 +16,10 @@ import org.springframework.stereotype.Component;
public class UtilEmailSent {
@Autowired
MailConfig mailConfig;
public void sendEmail(String to, String subject, String content){
sendEmail(to,subject,content, mailConfig.getNickname());
public int sendEmail(String to, String subject, String content){
return sendEmail(to,subject,content, mailConfig.getNickname());
}
public void sendEmail(String to, String subject, String content,String nickname) {
public int sendEmail(String to, String subject, String content,String nickname) {
JavaMailSender mailSender = mailConfig.getJavaMailSender();
MimeMessage mimeMessage = mailSender.createMimeMessage();
String from = mailConfig.getUsername();
@ -36,6 +36,27 @@ public class UtilEmailSent {
mailSender.send(mimeMessage);
}catch (Exception e){
log.error("(配置邮件失败){}",e.getMessage());
return -1;
}
return 1;
}
public int sendCode(String to){
String code = VerificationCodeGenerator.generateFourDigitCode();
String title=""+mailConfig.getNickname()+"】验证码 "+code;
String context="<div style=\"margin:10px auto;padding:2em;width:90%;min-height:480px;background-color:rgba(43,174,133,0.9);color:rgba(255,255,255,1);border-radius:5px;box-shadow:1px 0 10px 1px rgba(0,0,0,0.5)\">\n" +
"<h3>尊敬的用户:</h3>\n" +
"<p style=\"text-indent:2em;\">\n" +
"您正在乖乖狼科技旗下软件产品进行操作,您的验证码为\n" +
"<font color=\"yellow\" size=\"+2\">"+code+"</font>\n" +
",有效期为十分钟,请及时填写验证码。\n" +
"</p>\n" +
"<p style=\"text-indent:2em;\">如果这不是您本人操作,请忽略此邮件</p>\n" +
"<p style=\"float:right\">乖乖狼科技&nbsp;&nbsp;&nbsp;&nbsp;</p>\n" +
"</div>";
return sendEmail(to,title,context);
}
}

View File

@ -0,0 +1,27 @@
package com.guaiguailang.harmony.utils;
import java.util.Random;
public class VerificationCodeGenerator {
public static void main(String[] args) {
String verificationCode = generateFourDigitCode();
System.out.println("Generated Verification Code: " + verificationCode);
}
/**
* 生成一个四位数的验证码
* @return 四位数的验证码字符串
*/
public static String generateFourDigitCode() {
Random random = new Random();
StringBuilder code = new StringBuilder(4);
for (int i = 0; i < 4; i++) {
int digit = random.nextInt(10); // 生成一个0到9之间的随机整数
code.append(digit);
}
return code.toString();
}
}

View File

@ -1,7 +1,4 @@
package com.guaiguailang.harmony;
import com.guaiguailang.harmony.config.MailConfig;
import com.guaiguailang.harmony.service.EmailService;
import com.guaiguailang.harmony.utils.UtilEmailSent;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@ -11,8 +8,8 @@ class HarmonyLifeServerApplicationTests {
@Autowired
UtilEmailSent utilEmailSent;
@Test
void contextLoads() {
utilEmailSent.sendEmail("2952458479@qq.com","测试邮件标题","测试邮件内容");
void testEmailSentUtil() {
utilEmailSent.sendCode("2952458479@qq.com");
}
}