如何使用 spring boot 通过 outlook 发送邮件?

新手上路,请多包涵

我的 application.properties 文件包含以下配置:-

 spring.mail.properties.mail.smtp.connecttimeout=5000
  spring.mail.properties.mail.smtp.timeout=3000
  spring.mail.properties.mail.smtp.writetimeout=5000
  spring.mail.host=smtp.office365.com
  spring.mail.password=password
  spring.mail.port=587
  spring.mail.username=test@outlook.com
  spring.mail.properties.mail.smtp.starttls.enable=true
  security.require-ssl=true
  spring.mail.properties.mail.smpt.auth=true

用于实现邮件服务器的 Java 类是:

 @Component
public class SmtpMailSender {
@Autowired
private JavaMailSender javaMailSender;

public void sendMail(String to, String subject, String body) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    helper = new MimeMessageHelper(message, true);//true indicates multipart message
    helper.setSubject(subject);
    helper.setTo(to);
    helper.setText(body, true);//true indicates body is html
    javaMailSender.send(message);
}
}

我的控制器类是:

 @RestController
public class MailController {

@Autowired
SmtpMailSender smtpMailSender;

@RequestMapping(path = "/api/mail/send")
public void sendMail() throws MessagingException {
    smtpMailSender.sendMail("test123@outlook.com", "testmail", "hello!");
}
}

当我发送获取请求 (/api/mail/send) 时发生以下错误:

 {
"timestamp": 1496815958863,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.mail.MailAuthenticationException",
"message": "Authentication failed; nested exception is
javax.mail.AuthenticationFailedException: ;\n  nested exception
is:\n\tjavax.mail.MessagingException: Exception reading response;\n  nested
exception is:\n\tjava.net.SocketTimeoutException: Read timed out",
"path": "/api/mail/send"
}

任何帮助将不胜感激。

原文由 Ramesh Khadka 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 785
1 个回答

您必须指定 sender 使用 setFrom 方法在 outlook.com 上执行身份验证:

 @Component
public class SmtpMailSender {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String to, String subject, String body) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        helper = new MimeMessageHelper(message, true);//true indicates multipart message

        helper.setFrom(from) // <--- THIS IS IMPORTANT

        helper.setSubject(subject);
        helper.setTo(to);
        helper.setText(body, true);//true indicates body is html
        javaMailSender.send(message);
    }
}

outlook.com 会检查您是否试图假装自己是其他人。

原文由 frederik brooks 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题