springBoot发送邮箱验证码
一、在pom文件中添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
二、配置yaml文件
这里在yaml文件中配置好参数后,springboot会自动装配配置的邮箱参数。
spring:
mail:
host: smtp.qq.com #邮箱服务器地址
username: ******@qq.com #邮箱账号
password: laxoyuoaxatjigef #邮箱密码
default-encoding: utf-8 #默认编码
三、邮箱发送
package com.springBoot.learn.firstProject.manager.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Service; import com.springBoot.learn.firstProject.manager.SendCodeManager; @Service public class SendCodeImp implements SendCodeManager { @Autowired JavaMailSenderImpl mailSender; @Value("${spring.mail.username}") private String form; @Override public String sendMail(String to, String subject) throws Exception{ String code = getNumber(); SimpleMailMessage message = new SimpleMailMessage(); message.setSubject(subject); message.setText("注册验证码是:" + code); message.setTo(to); message.setFrom(form); //message.setFrom(to); mailSender.send(message); return code; } /** * 生成6位随机验证码 * @return */ public static String getNumber(){ String str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String code = ""; for(int i= 0;i<6;i++){ int index = (int)(Math.random()*str.length()); code+=str.charAt(index); } return code; } }

浙公网安备 33010602011771号