SpringBoot發送模板郵件

1、引入freemarker模塊的依賴:

org.springframework.bootspring-boot-starter-freemarker

2、在配置文件application.properties中加入配置信息:

spring.mail.host=郵箱主機

spring.mail.username=用戶名

spring.mail.password=密碼,一般這里是填寫授權碼

spring.mail.properties.mail.smtp.auth=true

spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.properties.mail.smtp.starttls.required=true

spring.freemarker.allow-request-override=false

spring.freemarker.cache=true

spring.freemarker.check-template-location=true

spring.freemarker.charset=UTF-8

spring.freemarker.content-type=text/html

spring.freemarker.expose-request-attributes=false

spring.freemarker.expose-session-attributes=false

spring.freemarker.expose-spring-macro-helpers=false

3、在resources中,新建一個名為templates的文件夾,并在其中創建一個模板頁面email.ftl:

你好,?${username},?這是一封模板郵件!

4、發送郵件代碼如下:


?出現錯誤:

異常如下:

Exception in thread "main" org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException

Caused by: javax.mail.AuthenticationFailedException

遇到這個異常首先檢查用戶名密碼配置是否正確,如果正確那就可能是郵箱的POP3/SMTP/IMAP服務沒有開啟,網易郵箱是默認關閉的,QQ郵箱也是默認關閉的。可以在郵箱的設置中開啟POP3/SMTP/IMAP服務,但是開啟該服務以后網易郵箱客戶端和配置文件中的登錄密碼就變成重新設置的授權碼了(記得修改配置文件中的密碼為授權碼,否則還是會報上述錯誤)。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容