注釋你的應用程序的主類(@SpringBootApplication注解,即類)與@EnableEmailTools: @SpringBootApplication
@EnableEmailTools
public class EmailApplication {public static void main(String[] args){SpringApplication.run(EmailApplication.class, args);}
}
讓我們編寫一個使用它的測試。ozimov.springboot.mail.service.EmailService bean發送電子郵件: @RunWith(SpringRunner.class)
@SpringBootTest
public class EmailServiceTest {@Autowired it.ozimov.springboot.mail.service.EmailService emailService; @Value("${spring.mail.username}") String fromEmail; @Test public void testSendEmail() throws UnsupportedEncodingException { User user = new User(); user.setEmail("sanaulla123@gmail.com"); user.setDisplayName("Mohamed Sanaulla"); final Email email = DefaultEmail.builder() .from(new InternetAddress(fromEmail, "From Name")).to(Lists.newArrayList(new InternetAddress(user.getEmail(), user.getDisplayName()))) .subject("Testing email").body("Testing body ...").encoding("UTF-8").build();emailService.send(email); }
}
如果一切順利,您應該在收件箱中收到一封電子郵件。
但是,當我嘗試上述代碼時,一切都不好,并且我遇到的問題是以下異常:
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14
<https://accounts.google.com/signin/continue?sarp=1?c=1&plt=AKgnsbs2
534-5.7.14 tEY84q9p029iw1YKFy_d8O1vYNwHLixZUNHZlZbIqZki9a-EBfcUTPIenD2i6pN704O_7S
534-5.7.14 DK4FC-8-l1K1gU537F4UxjN4v4_txZ5pqxEA8ATwDhmOBzvxAYApfJTQjHL1yhHouwbhGO
534-5.7.14 LhOzSAB6Va6u-enaDfcv73dEgv1TT4b19dBfgzIkOoz_7nJ3i-LwWxZqIRyxOEnu8iNIYQ
534-5.7.14 iV27v9s4HFOrpSOJNGufv1Hg0wU5s> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 q6sm2366693pgp.58 - gsmtp
發生此錯誤的原因是,我的Gmail / G Suite電子郵件(即使用自定義域的電子郵件)未配置為允許從安全性較低的應用(例如我們的應用)發送電子郵件。 為此,您需要訪問:https://www.google.com/settings/security/lesssecureapps并啟用“ 允許安全程度較低的應用程序 ”切換,如下所示: