2015-12-25 110 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

相关问题