![](https://img.haomeiwen.com/i10256255/82374c6b83da5a7f.png)
邮箱开启服务
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.yml
spring:
mail:
host: smtp.qq.com
username: email
password: password
properties:
mail:
smtp:
ssl:
enable: true
controller/SendEmail
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;
@RestController
public class SendEmail {
@Value(value = "${spring.mail.username}")
private String username;
@Autowired
private JavaMailSender javaMailSender;
@GetMapping("/send-email")
public String sendEmail(@RequestParam String to) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo(to);
message.setSubject("Your Verification Code");
// 生成验证码逻辑
String verificationCode = "123456"; // 示例验证码
message.setText("Your verification code is: " + verificationCode);
javaMailSender.send(message);
return "Email sent successfully";
} catch (Exception e) {
e.printStackTrace();
return "Failed to send email";
}
}
}
网友评论