首先在QQ邮箱中开启smtp服务并生成授权码
>然后在yml中添加配置
>spring:
#qq邮箱验证码
mail:
host: smtp.qq.com # 配置 smtp 服务器地址
port: 587 # smtp 服务器端口
username: xxx@qq.com #配置你的邮箱地址
password: xxx #配置申请到的授权码
protocol: smtp
defaultEncoding: utf-8
再然后写一个emailService用于发送验证码:
package com.starQeem.woha.service;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.mail.MessagingException;
/**
-
@Date: 2023/5/7 0:32
-
@author: Qeem
*/
@Component
public class emailService {
@Resource
private JavaMailSender javaMailSender;
public void sendVerificationCode(String form,String to, String code) throws MessagingException {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(form); //发送邮件的邮箱号
simpleMailMessage.setTo(to); //接收邮件的邮箱号
simpleMailMessage.setText("您的验证码为:"+code); //邮件内容
simpleMailMessage.setSubject("喔哈星"); //邮件标题
javaMailSender.send(simpleMailMessage); //发送
}
}
测试:
//测试邮箱发送
@Test
void testEmail() throws MessagingException {
emailService.sendVerificationCode("2572277647@qq.com","2572277647@qq.com","6666");
}
评论区