Spring Boot 透過 Gmail SMTP 寄信

 

 WordPress Useful Plugin – 使用 WP Mail SMTP 透過 GMail 來寄信 是讓 WordPress 可以透過 Goole API 的方式來寄信,而在 Spring Boot 中也可以透過客製程式來達成這功能。

 

  • 在 build.gradle 加入 dependencies: spring-boot-starter-mail
  1. compile("org.springframework.boot:spring-boot-starter-mail") // Mail

 

  • 在 application.properties 加入連結到 Gmail 的參數
  1. # =================================
  2. # Mail
  3. # =================================
  4. spring.mail.default-encoding=UTF-8
  5. # Gmail SMTP
  6. spring.mail.host=smtp.gmail.com
  7. # TLS , port 587
  8. spring.mail.port=587
  9. spring.mail.username=my.account@gmail.com
  10. spring.mail.password=my.password
  11.  
  12. # Other properties
  13. spring.mail.properties.mail.smtp.auth=true
  14. spring.mail.properties.mail.smtp.starttls.enable=true
  15. spring.mail.properties.mail.smtp.starttls.required=true

在 application.properties 這些的參數設定,也可以透過下方的程式碼來達成。

  1. @Configuration
  2. public class MailConfig {
  3.  
  4. @Bean
  5. public JavaMailSender getJavaMailSender() {
  6. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  7. mailSender.setHost("smtp.gmail.com");
  8. mailSender.setPort(587);
  9.  
  10. mailSender.setUsername("my.gmail@gmail.com");
  11. mailSender.setPassword("my.password");
  12.  
  13. Properties props = mailSender.getJavaMailProperties();
  14. props.put("mail.transport.protocol", "smtp");
  15. props.put("mail.smtp.auth", "true");
  16. props.put("mail.smtp.starttls.enable", "true");
  17. props.put("mail.smtp.starttls.required", "true");
  18. props.put("mail.debug", "true");
  19.  
  20. return mailSender;
  21. }
  22.  
  23. }

 

繼續閱讀:  Spring Boot 透過 Gmail SMTP 寄信

arrow
arrow
    文章標籤
    spring gmail
    全站熱搜

    MIS 發表在 痞客邦 留言(0) 人氣()