Spring Mail身份验证失败

时间:2018-12-03 08:27:00

标签: spring spring-mvc email

我正在尝试使用Spring Boot Mail API发送电子邮件。 这是我的代码

JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);

    mailSender.setUsername("xxx@gmail.com");
    mailSender.setPassword("xxx");

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;

但它不发送电子邮件,这是日志:

DEBUG: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed

2 个答案:

答案 0 :(得分:0)

如果您正在使用Spring Boot发送邮件,则只需配置以下属性即可。

application.properties

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

邮件发送方法

@Autowired
    public JavaMailSender emailSender;

    public void sendSimpleMessage(
      String to, String subject, String text) {
        ...
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setTo(to); 
        message.setSubject(subject); 
        message.setText(text);
        emailSender.send(message);
        ...
    }

答案 1 :(得分:0)

一切都正确,问题出在与Google的连接, 我不知道为什么,但是它解决了,现在我可以发送电子邮件了。