在Azure角色中使用SmtpClient时,“不支持请求的function”exception

我在Azure Web或Worker角色中使用SmtpClient时遇到exception。

我创建了一个控制台应用程序,通过RDP手动在角色VM上运行以重现:

using System; using System.Net; using System.Net.Mail; using System.Text; namespace ConsoleApplication1 { class Program { static void Main() { var mailClient = new SmtpClient("mail.redacted.com", 587); mailClient.EnableSsl = true; mailClient.DeliveryFormat = SmtpDeliveryFormat.International; mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; mailClient.UseDefaultCredentials = false;//SET THIS FIRST OR IT WIPES OUT CREDENTIALS NetworkCredential netCreds = new NetworkCredential("mail@redacted.com", "12345 same combination on my luggage"); mailClient.Credentials = netCreds; MailMessage message = new MailMessage(); message.SubjectEncoding = Encoding.UTF8; message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = false; message.From = new MailAddress("mike@redacted.com"); message.To.Add(new MailAddress("mike@redacted.com")); message.Subject = "testing " + DateTime.UtcNow; message.Body = "The quick brown fox jumped over the lazy dogs."; mailClient.Send(message); } } } 

在本地,它发送电子邮件就好了。 在Azure上我得到了这个:

    未处理的exception:System.Net.Mail.SmtpException:发送邮件失败。  ---> System.ComponentModel.Win32Exception:不支持请求的函数
       在System.Net.NTAuthentication.GetOutgoingBlob(Byte [] incomingBlob,Boolean throwOnError,SecurityStatus&statusCode)
       在System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob)
       在System.Net.Mail.SmtpNtlmAuthenticationModule.Authenticate(String challenge,NetworkCredential credential,Object sessionCookie,String spn,ChannelBinding channelBindingToken)
       在System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
       在System.Net.Mail.SmtpClient.Send(MailMessage消息)
        ---内部exception堆栈跟踪结束---
       在System.Net.Mail.SmtpClient.Send(MailMessage消息)
       位于c:\ development \ ConsoleApplication1 \ ConsoleApplication1 \ Program.cs中的ConsoleApplication1.Program.Main():第39行

我已经确认Azure计算机可以通过RDP在Azure角色上运行TCPing.exe来访问邮件服务器上的端口587。

显然问题是服务器之间的NTLM版本不匹配。

登录Azure角色并禁用客户端的“需要NTLMv2安全性”设置后,它可以工作:

在此处输入图像描述

(感谢这个答案和这个灵感的答案 。)

目前看看我们是否可以将我们的SMTP服务器升级为与NTLMv2兼容。 否则,我们必须设置一些自动代码,以某种方式在每个生成的角色实例上禁用该设置。

显然这个代码上个月有效。 所以我猜测最近的Azure OS升级改变了默认设置。

仅供参考:此设置的注册表项是

[HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Lsa \ MSV1_0]“NtlmMinClientSec”= dword:20000000

要自动设置注册表项,请添加包含reg add命令的启动任务 ,如下所示:

 reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0 ^ /v NtlmMinClientSec ^ /t REG_DWORD ^ /d 0x20000000 ^ /f 

其中/f强制覆盖当前设置,并且^只允许将命令分成多行以提高可读性。 还要确保以ASCII编码保存命令以防止在角色启动期间出现问题 。