赞
踩
我用的是163邮箱,优先需要授权码,如何开启授权码请参考链接
- <!-- 邮箱依赖-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
- spring:
- mail:
- host: smtp.163.com
- default-encoding: utf-8
- password: 授权码
- username: 自己的163邮箱
- properties:
- mail:
- smtp:
- ssl: enable=true
- @RestController
- public class MailController {
- @Value("${spring.mail.username}")
- private String from;
-
- @Autowired
- private JavaMailSender mailSender;
-
-
- @RequestMapping("/sendmail")
- public boolean sendMimeMail(String email, HttpSession httpSession) {
- try {
- //声明一个邮件发送请求
- SimpleMailMessage mailMessage=new SimpleMailMessage();
- //调用6位随机数随机数
- String code = randomCode();
- //将随机数放入Session中
- httpSession.setAttribute("email","要发送到的邮箱");
- httpSession.setAttribute("code",code);
- //邮件验证消息
- mailMessage.setSubject("邮件验证消息");
- //收到的验证码
- mailMessage.setText("收到的验证码:"+code);
- //发给谁
- mailMessage.setTo("要发送到的邮箱");
- //从哪发
- mailMessage.setFrom(from);
- //发送
- mailSender.send(mailMessage);
- return true;
- }catch (Exception e){
- e.printStackTrace();
- return false;
- }
- }
-
- //6位验证码
- public String randomCode(){
- StringBuilder stringBuilder = new StringBuilder();
- Random random=new Random();
- for (int i=0;i<6;i++){
- //从0-9中随机数
- stringBuilder.append(random.nextInt(10));
- }
- return stringBuilder.toString();
- }
-
- }
即可大功告成!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。