目录

springboot实现发送qq邮箱功能.md

李羽秋
李羽秋 2022年01月26日  ·  阅读 1,137

springboot实现发送qq邮箱功能

1.添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.配置datasource

spring:
 mail:
  host: smtp.qq.com #发送邮件服务器
  username: 510336979@qq.com #QQ邮箱
  password: fapvqlkhdjnvbjib #客户端授权码
  protocol: smtp #发送邮件协议
  properties.mail.smtp.auth: true
  properties.mail.smtp.port: 465 #端口号465或587
  properties.mail.display.sendmail: aaa #可以任意
  properties.mail.display.sendname: bbb #可以任意
  properties.mail.smtp.starttls.enable: true
  properties.mail.smtp.starttls.required: true
  properties.mail.smtp.ssl.enable: true #开启SSL
  default-encoding: utf-8

3.编写个人邮件服务Service

@Service
public class MailService {
    @Resource
    private JavaMailSender javaMailSender;
    //从配置文件中注入发件人的姓名
    @Value("${spring.mail.username}")
    private String fromEmail;

    public void sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        javaMailSender.send(message);
    }
}

4.测试

@Test
void contextLoads() {
    mailService.sendSimpleMail("510336979@qq.com","普通文本邮件","我是李羽秋");
}
分类:
标签: