SMTP客户端在本地主机上发送消息失败,在远程主机上发送成功

本文关键字:主机 程主机 成功 失败 客户端 SMTP 消息 | 更新日期: 2023-09-27 18:01:58

我有一个小型tcp服务器,用于通过SMTP服务器发送邮件。

问题是,当我在我的开发机器(远程连接到smtp服务器)上运行它时,它可以正常工作,但是当我在与smtp服务器(Windows server 2008 R2)相同的机器上运行应用程序时,我得到以下例外:

System.Net.Mail。SmtpException:发送邮件失败。--> System.IO.IOException: cannot to read data from transport connection: net_io_connectionclosed.

SMTP服务器被配置为只允许来自127.0.0.1和tcp应用程序绑定的IP地址的中继,以及我的开发机器。它还被配置为只允许来自相同IP列表的连接。

发送邮件的c#位如下:

var mail = new MailMessage();
mail.To.Add(recipient);
mail.From = new MailAddress("me@mydomain.com");
mail.Subject = "subject";
mail.Body = "message";
var smtpClient = new SmtpClient(MailServerAddress, Constants.MAIL_SERVER_PORT);         
smtpClient.Send(mail);

MailServerAddress是在应用程序首次运行时定义的。我已经尝试将其设置为127.0.0.1和SMTP服务器配置的IP地址,但我仍然得到相同的异常。

检查服务器日志显示没有连接的迹象,这符合上述异常。

我在这里做错了什么?

SMTP客户端在本地主机上发送消息失败,在远程主机上发送成功

只是一个黑暗的答案,但尝试这个,因为我有一个类似的问题,大约3年前,但不记得修复,但这行代码脱颖而出,当我有一个看

_client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

所以也许可以尝试(假设您使用IIS为SMTP):

var smtpClient = new SmtpClient(MailServerAddress, Constants.MAIL_SERVER_PORT); 
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;        
smtpClient.Send(mail);

答案从这里复制过来:

Unable to read data from the transport connection: net_io_connectionclosed

What this error means is that System.net.mail was unable to find the smtp server.
The answer will vary depending on whether you have a fixed IP or a dynamic IP but,
basically, you need to assign a valid IP to your smtp server.
With fixed IP's this is relatively straightforward.
With dynamic IP's it takes a bit of tweaking.
Open the IIS Manager and check the properties for the smtp server.
In the Default SMTP Virtual Server's properties, in the "Access" tab,
in the Connection Control and Relay dialogs, make sure that your local IP is assigned.
( In my case, it's 10.0.0.2... )
You may also need to modify your hosts file, to point 127.0.0.1 to your machine name.
( 'WINDOWS'system32'drivers'etc'hosts )
Then, in your code, assign your machine name to the smtp client :
SmtpClient client = New SmtpClient("yourmachinename")
client.Send(mail)

另一种情况是你可能有防火墙阻止你的测试。如果可以,在不构成安全风险的情况下,断开与互联网的连接并禁用防火墙。看看它是否有效。如果是这样,您需要更深入地查看防火墙设置。如果不是,它真的可能是你的IP地址,如上所述。