无法连接到SMTP主机:localhost,port:25;嵌套异常是:java.net.ConnectException:连接被拒绝:连接

时间:2011-03-03 10:58:22

标签: email jsp

我正在申请发送来自localhost的电子邮件jsp&我发现错误如无法连接到SMTP主机:localhost,端口:25;嵌套异常是:java.net.ConnectException:连接被拒绝:连接 请检查并给我解决方案或想法,如果你有.for我正在使用下面的代码。  提前感谢你。

 <%@ page language="java" import="javax.naming.*,java.io.*,javax.mail.*,
javax.mail.internet.*,com.sun.mail.smtp.*"%>

<html>
<head>
<title>Mail</title>
</head>

<body>

<%
try{
  Session mailSession = Session.getInstance(System.getProperties());

  Transport transport = new SMTPTransport(mailSession,new URLName("localhost"));

  transport.connect("localhost",25,null,null);


  MimeMessage m = new MimeMessage(mailSession);

  m.setFrom(new InternetAddress(%><%request.getParameter("from")%><%));

  Address[] toAddr = new InternetAddress[] {
              new InternetAddress(%><%request.getParameter("to")%><%)
            };
  m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );

  m.setSubject(%><%request.getParameter("subject")%><%);

  m.setSentDate(new java.util.Date());

  m.setContent(%><%request.getParameter("description")%><%, "text/plain");

  transport.sendMessage(m,m.getAllRecipients());

  transport.close();

  out.println("Thanks for sending mail!");
}
catch(Exception e){

  out.println(e.getMessage());
  e.printStackTrace();
}
%>


</body>

</html>

2 个答案:

答案 0 :(得分:13)

首先,您必须确保在端口25上侦听SMTP服务器。

要查看您是否拥有该服务,您可以尝试使用TELNET客户端,例如:

C:\> telnet localhost 25

(默认情况下,telnet客户端在最新版本的Windows上禁用,您必须从控制面板添加/启用Windows组件。在Linux / UNIX中,默认情况下通常会有telnet客户端。

$ telnet localhost 25

如果等待很长时间然后超时,则表示您没有所需的SMTP服务。如果成功连接,您输入内容并能够输入内容,服务就在那里。

如果您没有该服务,可以使用以下内容:

  • 模拟SMTP服务器,它将模仿实际SMTP服务器的行为,因为您正在使用Java,建议使用Dumbster假SMTP服务器是很自然的。这甚至可以在JUnit测试中使用(使用设置/拆除/验证),或者作为独立的集成测试流程独立运行。
  • 如果你的主机是Windows,你可以在运行上面的代码之前尝试在你的本地安装Mercury email server(也来自Apache Friends的WAMPP包)。
  • 如果您的主机是Linux或UNIX,请尝试启用邮件服务,例如Postfix
  • Java中另一个完整的SMTP服务器,例如Apache James邮件服务器。

如果您确定已经拥有该服务,则SMTP可能需要其他安全凭据。 如果您可以告诉我在端口25上侦听的SMTP服务器,我可能会告诉您更多信息。

答案 1 :(得分:1)

CentOS 6上的邮件服务器和其他支持IPv6的服务器平台可能绑定到IPv6 localhost(:: 1)而不是IPv4 localhost(127.0.0.1)。

典型症状:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

如果发生这种情况,请确保localhost/etc/hosts有两个不同IP地址的条目,例如:(错误)示例:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

为避免混淆,请确保只有localhost的一个条目,最好是IPv4地址,如下所示:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6