赞
踩
场景:用户登录时忘记密码,需要通过邮箱找回密码
1.创建springboot项目
2.pom导入依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
3.application.properties配置文件
- spring.mail.host=smtp.163.com
- spring.mail.username=sple_vip@163.com//发件人邮箱,需要开启smtp服务
- spring.mail.password=ming438434//授权密码,非邮箱的登录密码
- spring.mail.port=25
- spring.mail.protocol=smtp
- spring.mail.default-encoding=UTF-8
发件人邮箱的设置:
邮箱客户端授权码也需要手动开启,设置授权码
4.用户输入自己的邮箱,点击找回,前端页面
html代码:
- <div class="regWrap">
- <div class="regName">
- <span>请输入邮箱</span>
- <input id="mail" type="email" class="mail" placeholder="请输入邮箱">
- </div>
- <button id="registbtn" class="regBtn" type="button">找回</button>
- </div>
js代码:
- $(function () {
- $("#registbtn").click(function() {
- var user = {
- mail:$("#mail").val()
- }
- $.ajax({
- type: "POST",
- url:"/mail.action",
- contentType: "application/json;",
- data: JSON.stringify(user),
- success: function (data) {
- if(data == "successful"){
- alert("已发送至您的邮箱")
- location.href="/login.html";
- }
- if (data=="failful") {
- alert("邮箱错误")
- }
- },
- error: function (data) {
- alert("网络繁忙")
- }
- });
-
- });
- });
5.点击找回,进入controller层
- @RequestMapping("/mail.action")
- public String mail(@RequestBody User user) {
- return mailService.sendMail(user);
- }
service层
- @Service
- public class MailServiceImpl implements MailService{
- @Autowired
- private JavaMailSender javaMailSender;
- @Autowired
- private UserMapper userMapper;
- @Override
- public String sendMail(User user) {
- User user2 = mailPwd(user);
- StringBuilder stringBuilder=new StringBuilder();
- stringBuilder.append("<html><head><title></title></head><body>");
- stringBuilder.append("亲爱的用户"+user2.getAccount()+",您的当前密码是:"+user2.getPassword());
- stringBuilder.append("</br><a href='https://www.baidu.com/'>访问百度</a></body><html>");
- MimeMessage mimeMessage=javaMailSender.createMimeMessage();
- //multipart模式
- try {
- MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage, true);
- mimeMessageHelper.setTo(user.getMail());//收件人邮箱user.getMail()
- mimeMessageHelper.setFrom("sple_vip@163.com");//发件人邮箱
- mimeMessage.setSubject("找回密码");
- //启用html
- mimeMessageHelper.setText(stringBuilder.toString(),true);
- javaMailSender.send(mimeMessage);
- return Constent.SUCCESSFUL;
- } catch (MessagingException e) {
- e.printStackTrace();
- return Constent.FAILFUL;
- }
- }
-
- /**
- * 通过邮箱到数据库查询用户的信息
- */
- @Override
- public User mailPwd(User user) {
- return userMapper.mailPwd(user);
- }
-
- }
dao层
- public interface UserMapper {
- /**
- * 通过邮箱查询用户信息
- */
- @Select("SELECT * FROM user WHERE mail = #{mail}")
- public User mailPwd(User user);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。