使用Java发送电子邮件时出错

时间:2015-03-23 15:49:44

标签: java email smtp



我在使用Java发送电子邮件时遇到问题。我正在使用JavaMail api发送电子邮件。我有一个程序,使用pop3下载电子邮件附件,读取内容,进行一些操作,然后使用smtp将结果发送到电子邮件中。

该程序正常工作,直到它发送电子邮件的最后一步,我得到以下异常。

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
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 com.adidas.monitoring.SendMail.sendMail(SendMail.java:46)
at com.adidas.monitoring.MainClass.main(MainClass.java:115)
Caused by: java.net.ConnectException: Connection refused: 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:1927)

我使用以下代码发送电子邮件

public void sendMail(String strMailContent) 
{       
    MimeMessage emailMessage;

    Properties emailProperties = new Properties();
    try {
        emailProperties.load(new FileInputStream("Email.ini"));
    } catch (IOException e){
        DataLogger.logger.error(e.getMessage());
    }

    /*Get the properties from the email configuration file*/
    String From = emailProperties.getProperty("Email.From");
    String ToAdd = emailProperties.getProperty("Email.To");
    String CC = emailProperties.getProperty("Email.CC");
    String Subject = emailProperties.getProperty("Email.Subject");
    String Host = emailProperties.getProperty("Email.Gateway");
    emailProperties.setProperty("mail.smtp.host", Host);
    Session emailSendSession = Session.getDefaultInstance(emailProperties);

    try{         
        emailMessage = new MimeMessage(emailSendSession);
        emailMessage.setFrom(new InternetAddress(From));
        emailMessage.addRecipients(javax.mail.Message.RecipientType.TO,ToAdd);
        emailMessage.addRecipients(javax.mail.Message.RecipientType.CC,CC);
        emailMessage.setSubject(Subject);
        emailMessage.setText(strMailContent);

        Transport.send(emailMessage);
    }
    catch (Exception mailEx) 
    {
        mailEx.printStackTrace();
    }
}

以上代码与其他程序一起使用时效果很好。但是当我在这种情况下使用它和pop3代码时,我有这个错误。奇怪的是,即使我将属性设置为“mail.smtp.host”,主机也显示为localhost。

非常感谢您对此主题的任何帮助。

0 个答案:

没有答案