首页 > 技术文章 > SpringBoot使用Google发送邮件

IamHzc 2021-10-17 15:59 原文

1.导入依赖

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

2.配置application.properties

spring.mail.host=smtp.gmail.com
spring.mail.username=hzc1019@gmail.com
spring.mail.password=Onetwo12..
spring.mail.port=465
#587
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.required=true

#两个端口一个不行就试一下另外一个
# SSL, post 465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory

3.使用

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private ApplysService applysService;
    @Value("${spring.mail.username}")
    private String from;
  
    /**
      to:接收方
      from:发送方
      subject:邮件标题
      text:邮件内容
    **/
    @PostMapping("/isThrough")
    public void sendIsThrough(Integer id){
        EmailInfo email = applysService.getEmailInfo(id);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(email.getSubject());
        System.out.println("目标邮箱:"+email.getTo());
        message.setTo(email.getTo());
        message.setText(email.getText());
        javaMailSender.send(message);
    }
}

推荐阅读