2017-06-07 107 views
0

我application.properties文件包含以下配置: -如何通过outlook使用spring启动邮件发送邮件?

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 
    [email protected] 
    spring.mail.properties.mail.smtp.starttls.enable=true 
    security.require-ssl=true 
    spring.mail.properties.mail.smpt.auth=true 

为implemting邮件服务器的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("[email protected]", "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" 
} 

任何帮助将受到热烈的赞赏。

+0

请参阅https://stackoverflow.com/questions/14430962/send-javamail-using-office365 – user7294900

+0

邮件服务器连接失败;嵌套的异常是com.sun.mail.util.MailConnectException:无法连接到主机,端口:smtp-mail.outlook.com,995; 谢谢你的帮助。 –

+0

@ user7294900我尝试了给定链接中提供的解决方案,但它不起作用。感谢您的帮助 –

回答

0

您必须指定使用sendersetFrom方法对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检查,你不是要假装你是别人。

相关问题