2015-12-25 116 views
0

我正在使用Java Spring,Maven和我試圖使用gmail id在gmail上發送郵件。我收到此錯誤:首先必須發出STARTTLS命令。 mail.smtp.EnableSSL.enable已設置爲true

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 11sm885884pfp.38 - gsmtp 

甚至通過我已經設置了參數

mail.smtp.starttls.enable 

爲true。

這是我的函數:

public String sendMail(String to, String subject, String textMessage) throws IOException { 
    Properties props = new Properties(); 
    props.put("mail.transport.protocol", "smtp"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.auth", "true"); 
    Session mailSession = Session.getInstance(props); 
    mailSession.setDebug(true); 
    Message simpleMessage = new MimeMessage(mailSession); 

    InternetAddress fromAddress = [email protected]; 
    InternetAddress toAddress = null; 
    try { 
     toAddress = new InternetAddress(to); 
    } catch (AddressException e) { 
     System.out.print("\nError in Address of Sender or reciever\n"); 
     e.printStackTrace(); 
    } 
    try { 
     simpleMessage.setFrom(fromAddress); 
     simpleMessage.setRecipient(RecipientType.TO, toAddress); 
     simpleMessage.setSubject(subject); 
     simpleMessage.setText(textMessage); 
     SMTPTransport t = (SMTPTransport) mailSession.getTransport("smtp"); 
     t.setStartTLS(true); 
     t.connect("smtp.gmail.com", "[email protected]", "from.password!"); 
     t.sendMessage(simpleMessage, simpleMessage.getAllRecipients()); 
     t.close(); 

    } catch (MessagingException e) {    
     System.out.print("\nError in message Genration\n"); 
     e.printStackTrace(); 
    } 
    return "success"; 
} 

所有的SO告訴我們設置mail.smtp.starttls.enable到真正的答案。這樣做甚至不起作用。

我也包括在我的POM中javax.mail依賴性爲:

<dependency> 
    <groupId>javax.mail</groupId> 
    <artifactId>mail</artifactId> 
    <version>1.4</version> 
</dependency> 

回答

0

當你使用Spring,這是更好地整合,而不是javax.mail底層API的抽象。實際上,您可以使用JavaMailSender及其實現JavaMailSenderImpl來實現相同的結果。一個例子見this

相關問題