所以我正在尝试设置一个 Spring Boot 应用程序来发送自动电子邮件。我专门为此目的创建了一个 Gmail 帐户。我按照教程指导我为我的 Gmail 帐户设置两步身份验证,并设置应用程序密码来登录。我这样做了,一切工作正常,我从应用程序发送了一封测试电子邮件,它工作了。然而,在没有进行任何代码更改的情况下,我在几个小时后再次尝试了该过程,并收到以下消息:
Exception in thread "main" org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at
534 5.7.9 https://support.google.com/mail/?p=WebLoginRequired v8-20020a05683018c800b005cb39fc3e15sm11417144ote.13 - gsmtp
这是我的 application.properties 文件:
spring.mail.protocol=smtp
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
mail.smtp.debug=true
这是我的邮件服务(尽管此错误发生在应用程序启动时,所以我不认为这是原因)
@Service("mailService")
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail(Mail mail) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setSubject(mail.getMailSubject());
mimeMessageHelper.setFrom(new InternetAddress(mail.getMailFrom(), "tyler"));
mimeMessageHelper.setTo(mail.getMailTo());
mimeMessageHelper.setText(mail.getMailContent());
mailSender.send(mimeMessageHelper.getMimeMessage());
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
我已尝试按照链接寻求建议,但它建议我使用应用程序密码(我已经是)或启用“不太安全的应用程序”(作为 2FA 用户,我不能这样做)。任何帮助将不胜感激。
如果您使用 spring-boot-starter-mail,请尝试将其添加到您的 pom 中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
这对我有用