看了心血来潮,我要是实现springboot的验证码接口发送,网上一搜,就找到不少教程
笔者的邮箱是126,配置的时候要开ssl
简易邮件发送,到接口邮件发送
note 内容简易的发送邮件方法就只需要简易的配置
spring.mail.username=scwelcome@126.com spring.mail.password=HOYROCEIIGJDFOAP spring.mail.host=smtp.126.com
然后自己就是随便写一个测试类或者main
@SpringBootTest class DemoApplicationTests {
@Autowired JavaMailSenderImpl mailSender;
@Test void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo("runformoon@foxmail.com");
message.setFrom("scwelcome@126.com");
message.setSubject("你好哇!!!");
message.setText("57236+54345=?");
mailSender.send(message);
}
}
首先加入springBoot依赖
org.springframework.boot spring-boot-starter-mail
加好之后,在配置文件application.properties加配置
#发件人邮箱服务器相关配置 spring.mail.host=smtp.126.com spring.mail.port=465 #spring.mail.port=587 #配置个人QQ账号和密码(密码是加密后的授权码) spring.mail.username=###你的126邮箱### spring.mail.password=###你的授权码### spring.mail.default-encoding=utf-8 # SSL 配置 spring.mail.protocol=smtp spring.mail.properties.mail.smtp.ssl.enable=true spring.mail.properties.mail.smtp.socketFactory.port=465 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
要写接口那就要加上上面的ssl
并且写controller层EmailController.java(自己导包)
@RestController
public class EmailController {
@Autowired
EmailService emailService= new EmailService() ;
@GetMapping("/name/{to}/code/{sub}")
public String sendSimpleEmail(@PathVariable("to") String to,@PathVariable("sub") String sub) {
String subject="阿狸科技的验证码是" + sub ;
String text="Hello World";
emailService.sendSimpleEmail(to, subject, text);
return "邮件发送成功";
}
}
service层@Service.java (自己导包)
@Service
public class EmailService {
@Autowired
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}")
private String from;
//纯文本邮件信息发送
public void sendSimpleEmail(String to,String subject,String text) {
//定制纯文本邮件信息SimpleMailMessage
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
ok算是大功告成了
浏览器输入
localhost:8080/name/###你的邮箱###/code/##验证码##
发送成功



