2013-07-22 234 views
0

我想使用javax.mail從[email protected]發送郵件到[email protected]。我已經嘗試了下面的代碼,但它給出了我也在下面提到的錯誤。歡迎任何幫助。使用javax.mail發送消息

Properties prop = new Properties(); 
    Session sess = Session.getDefaultInstance(prop,null); 

    Message msg = new MimeMessage(sess); 
    msg.setFrom(new InternetAddress("[email protected]", "Sender")); 
      msg.addRecipient(Message.RecipientType.TO, 
         new InternetAddress("[email protected]", "Receiver")); 
      msg.setSubject("Your Example.com account has been activated"); 
      msg.setText("Testing messgage"); 
      Transport.send(msg); 


} 

產生的錯誤是

Exception in thread "main" javax.mail.MessagingException: Could not connect to
SMTP host: localhost, port: 25; nested exception is: java.net.SocketException: Permission denied: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1962) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at MAIL.sendmail.main(sendmail.java:41) Caused by: java.net.SocketException: Permission denied: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1928) ... 7 more

回答

0

您設置的屬性的SMTP服務器對象在自己的機器(本地主機),這顯然是不運行在端口上的SMTP服務器25.我認爲你想使用現有的SMTP服務器(例如你從互聯網提供商那裏獲得的服務器,或者GMail爲你提供的服務器等等)。

+0

是的,我想用戶的Gmail – user2575804

1

下面的示例性使用Gmail發送電子郵件:

private Properties createConfiguration() { 
    return new Properties() {{ 
     put("mail.smtp.auth", "true"); 
     put("mail.smtp.host", "smtp.gmail.com"); 
     put("mail.smtp.port", "587"); 
     put("mail.smtp.starttls.enable", "true"); 
    }}; 
}