2014-12-06 56 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