System.Net.Mail.SMTPClient如何执行其本地IP绑定

我们有一个负载均衡(NLB)ASP.NET Web应用程序,它发送电子邮件。

服务器是双归属的,具有面向外部和内部(在防火墙后面)面向IP。 邮件服务器位于防火墙后面。

我们一直在遇到一个问题,即SMTPClient类抛出exception,指出它无法连接到SMTP服务器。

网络人员告诉我们他们正在尝试从面向外部的IP地址(防火墙阻止)连接到SMTP服务器

从我对网络启用的应用程序的知识(不可否认的)我认为本地IP绑定将根据目的地决定,即如果路由表说IP地址可以通过特定的NIC访问,那么IP就是出站请求是从…生成的。 我错了吗?

看着SmtpClient.ServicePoint我开始认为我们可能并且我们可以(应该)强制显式绑定到特定的IP?

特别是我一直在看
该页面的ServicePoint.BindIPEndPointDelegate属性 ……

备注:某些负载平衡技术要求客户端使用特定的本地IP地址和端口号,而不是IPAddress.Any(或Internet协议版本6的IPAddress.IPv6Any)和临时端口。 您的BindIPEndPointDelegate可以满足此要求。

对我来说这似乎有点奇怪,我需要这样做,但也许在这种环境中常见?

你需要做这样的事……

public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount); private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { if (retryCount < 3 && ddSendFrom.SelectedValue.Length > 0) return new IPEndPoint(IPAddress.Parse("192.168.1.100"), 0); //bind to a specific ip address on your server else return new IPEndPoint(IPAddress.Any, 0); } protected void btnTestMail_Click(object sender, EventArgs e) { MailMessage msg = new MailMessage(); msg.Body = "Email is working!"; msg.From = new MailAddress("me@me.com"); msg.IsBodyHtml = false; msg.Subject = "Mail Test"; msg.To.Add(new MailAddress("you@you.com")); SmtpClient client = new SmtpClient(); client.Host = "192.168.1.1"; client.Port = 25; client.EnableSsl = false; client.ServicePoint.BindIPEndPointDelegate = new System.Net.BindIPEndPoint(BindIPEndPointCallback); client.Send(msg); }