2017-06-07 106 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檢查,你不是要假裝你是別人。

相關問題