文章目录
代码展示
导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
增加配置类yml
mail: host: smtp.qq.com port: 587 username: 写qq邮箱 password: 在qq邮箱设置>账户>开启POP3/SMTP服务时获得 default-encoding: UTF-8 properties: smtp: socketFactoryClass: javax.net.ssl.SSLSocketFactory debug: true
service接口
/** * 发送邮件 * @param email 邮箱 * @param session session会话 * @return boolean */ boolean sendMail(String email, HttpSession session);
service实现
@Autowired protected SendMail sendMail; @Override public boolean sendMail(String email, HttpSession session) { String code = sendMail.sendSimpleMail(email); session.setAttribute("code",code); System.out.println(code); QueryWrapper<UserBean> wrapper = new QueryWrapper<>(); wrapper.inSql("id","select id from tab_member where member_mail= "+"\""+email+"\""); UserBean user = userMapper.selectOne(wrapper); session.setAttribute("password",user.getMemberPassword()); return code != null; }
manager增加SendMail类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import java.util.Date; import java.util.Random; /** * @Author: Ljx * @Date: 2021/5/22 9:24 */ @Component public class SendMail { @Autowired JavaMailSender javaMailSender; int max = 99999; int min = 10000; Random random = new Random(); public String sendSimpleMail(String email){ int s = random.nextInt(max-min+1) + min; String code = String.valueOf(s); SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("找回密码"); message.setFrom("写qq邮箱"); message.setTo(email); message.setSentDate(new Date()); message.setText("你的验证码是:"+code); javaMailSender.send(message); return code; } }
controller
@PostMapping("/sendEmail") @ApiOperation(value = "发送验证码", notes = "邮箱不能为空", httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "email", value = "邮箱", required = true, dataType = "String"), }) public RespBean sendEmail(String email, HttpSession session){ boolean judgment = iUserService.sendMail(email,session); if (judgment){ String returnCode = (String) session.getAttribute("code"); logger.info("发送验证码成功"); return RespBean.ok("发送验证码成功",returnCode); }else{ logger.error("发送验证码失败"); return RespBean.error("发送验证码失败"); } }