new MailMessage() Throws 'The handle is invali

2019-08-01 15:50发布

问题:

Why does this code:

MailMessage mm = new MailMessage();

Throw this exception:

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: 

My Web.config

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

回答1:

Why it throws it? probably because MS is doing something goofy under the covers.

IIRC, that SecureString code actually makes an interop call down to advapi32.dll.

My knee jerk reaction is to:

  1. Disable any antivirus software, and see if that fixes it.

  2. Make sure you have access to that dll.



回答2:

I believe instantiating the MailMessage doesn't read from the Web.config. The SmtpClient reads the SMTP set up in the web.config.

Can you show more of your code? Maybe the rest of the GetMailMessage method.