new MailMessage()抛出'句柄无效'

时间:2012-03-07 22:58:12

标签: c# asp.net asp.net-4.0 system.net.mail

为什么这段代码:

MailMessage mm = new MailMessage();

抛出此异常:

System.Security.Cryptography.CryptographicException was caught
Message=The handle is invalid.

Source=mscorlib
StackTrace:
   at System.Security.SecureString.ProtectMemory()
   at System.Security.SecureString.InitializeSecureString(Char* value, Int32 length)
   at System.Security.SecureString..ctor(Char* value, Int32 length)
   at System.Net.UnsafeNclNativeMethods.SecureStringHelper.CreateSecureString(String plainString)
   at System.Net.Configuration.SmtpNetworkElementInternal..ctor(SmtpNetworkElement element)
   at System.Net.Configuration.SmtpSectionInternal..ctor(SmtpSection section)
   at System.Net.Configuration.SmtpSectionInternal.GetSection()
   at System.Net.Mail.SmtpClient.get_MailConfiguration()
   at System.Net.Mail.MailMessage..ctor()
   at csEmail.GetMailMessage(String subject, String htmlbody) in c:\Users\Greg\My Dropbox\Intern Files\mobiledesign\App_Code\Utilities.cs:line 364
InnerException: 

我的Web.config

<smtp deliveryMethod="Network" from="correctAddress">
    <network host="smtp.gmail.com" userName="correctAddress" password="correctPassword" enableSsl="true" port="587"/>
</smtp>

2 个答案:

答案 0 :(得分:0)

我认为实例化MailMessage不会从Web.config中读取。 SmtpClient读取web.config中设置的SMTP。

你能展示更多代码吗?也许是GetMailMessage方法的其余部分。

答案 1 :(得分:0)

为什么抛出它?可能是因为MS正在做一些愚蠢的事情。

IIRC,SecureString代码实际上是对advapi32.dll进行互操作调用。

我的膝跳反应是:

  1. 禁用所有防病毒软件,看看是否有解决方法。

  2. 确保您可以访问该dll。