2014-12-06 100 views
0

請有人請徹底,幫助我,我現在一直在這個。我在編程方面有點新,我以前從未設置過服務器或其他任何東西。我得到這個錯誤試圖運行我的程序。 「java.net.ConnectException: Connection refused: connect」和「javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;單擊JButton時發送電子郵件?

這裏是我的代碼

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
if (jButton1.isEnabled()); 
Properties sessionProperties = System.getProperties(); 
String to = "[email protected]"; 
    String from = "[email protected]"; 
    String host = "localhost"; 
    Properties properties = System.getProperties(); 
    properties.setProperty("mail.smtp.host", host); 
    Session session = Session.getDefaultInstance(properties); 

    try{ 
    // Create a default MimeMessage object. 
    MimeMessage message = new MimeMessage(session); 

    // Set From: header field of the header. 
    message.setFrom(new InternetAddress(from)); 

    // Set To: header field of the header. 
    message.addRecipient(Message.RecipientType.TO, 
           new InternetAddress(to)); 

    // Set Subject: header field 
    message.setSubject("Infomation"); 

    // Now set the actual message 
    message.setText("Hello!"); 

    // Send message 
    Transport.send(message); 

    }catch (MessagingException mex) { 
    mex.printStackTrace(); 

回答

0

它看起來像你的代碼http://www.tutorialspoint.com/java/java_sending_email.htm 來到如果是的話,我想你直接來了句的嘖嘖

Here it is assumed that your localhost is connected to the internet and capable enough 
to send an email. 

通過能力,這意味着你有一個SMTP服務器上運行本地主機;你得到這個例外的原因是因爲Transport試圖在localhost:25上使用SMTP服務器來發送郵件。

然後,您的選擇是在本地運行SMTP服務器(真正的痛苦)或使用第三方SMTP(GMail,Amazon SES等)服務來發送郵件。

+0

非常感謝您的幫助和迴應!請解釋我如何使用上面的代碼使用第三方SMTP?我知道我不能在動作偵聽器中使用公共類和所有這些,這就是爲什麼我沒有使用任何其他代碼。我非常感謝您的回覆。 – TheCoder233 2014-12-06 04:33:10

+0

查看使用Gmail作爲SMTP服務的示例:http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ 如果您選擇前往有更多的企業選項(我不知道你寫的代碼的範圍),亞馬遜SES可能是你最好的選擇。它有一個完善的SDK(請參閱:http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-java.html),並與其他亞馬遜服務很好地集成。 – 2014-12-06 04:34:54

+0

我看了那個例子,但是他開始說明一個公共類,我不能在一個動作監聽器中做。 (或者至少我不確定如何。)如果是這樣,我如何在動作監聽器中使用該代碼?非常感謝你的回覆! – TheCoder233 2014-12-06 04:37:36