一、添加spring-boot-starter-mail
<!--邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、添加yml配置
spring:
mail:
host: smtp.163.com
password: 邮箱授权码不是密码
username: 163邮箱
port:
default-encoding: UTF-8
protocol: smtp
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
mail.smtp.socketFactory.port: 465
mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback: false
三、发送邮件实现
public interface MailService {
boolean sendMail(String to, String subject, String text);
}
@Service
public class MailServiceImpl implements MailService {
private final JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public MailServiceImpl(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
@Override
public boolean sendMail(String to, String subject, String text) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom(from);
msg.setTo(to);
msg.setSubject(subject);
msg.setText(text);
try {
mailSender.send(msg);
} catch (MailException ex) {
System.err.println(ex.getMessage());
return false;
}
return true;
}
}
四、调用接口发送测试邮件
@RestController
@RequestMapping("mail")
public class EmailController {
@Autowired
MailService mailService;
@RequestMapping("send")
public void sendMail(){
mailService.sendMail("595506841@qq.com","test","test");
}
}