我的 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);
}
}
我的 Controller 类是:
@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"
}
我们将不胜感激任何帮助。
最佳答案
您必须使用 setFrom
方法指定 sender
才能在 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 会检查您是否试图假装自己是其他人。
关于java - 如何使用 spring boot 通过 outlook 发送邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44405168/