6

I am getting exception while sending mail through C# for

SmtpClient client = new SmtpClient() 

as System.Security.Cryptography.CryptographicException: The handle is invalid.

MailMessage mail = new MailMessage(from,to);

            mail.To.Add(to);
            mail.From = new MailAddress(from, "", System.Text.Encoding.UTF8);

            mail.Subject = "This is a test mail";

            mail.SubjectEncoding = System.Text.Encoding.UTF8;

            mail.Body = fr.message;

            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.IsBodyHtml = true;

            mail.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient();

            //Add the Creddentials- use your own email id and password
            client.Credentials = new System.Net.NetworkCredential(from, Password);

            client.Port = 587; // Gmail works on this port

            client.Host = "smtp.gmail.com";

            client.EnableSsl = true; //Gmail works on Server Secured Layer

                client.Send(mail);

I am not getting why this happens?

user
  • 793
  • 4
  • 14
  • 23
  • possible duplicate of [new MailMessage() Throws 'The handle is invalid'](http://stackoverflow.com/questions/9610424/new-mailmessage-throws-the-handle-is-invalid) – V4Vendetta Aug 13 '12 at 10:10
  • isn't the port `465` for ssl ? – V4Vendetta Aug 13 '12 at 10:14
  • This is not a duplicate. The other question had the exception on the `MailMessage` constructor, but here it happens on the `SmtpClient` constructor. Also, the other question has no real answer. – John Saunders Aug 13 '12 at 21:02
  • 2
    Try wrapping your MailMessage and SmtpClient in `using` blocks: `using (var mail = new MailMessage(...)){ ... using (var client = new SmtpClient(...)){ ...}}` – John Saunders Aug 13 '12 at 21:03
  • This code works well on my machine. What platform do you use? – dvvrd Aug 14 '12 at 07:39
  • 1
    i found a solution in another threat. Please check http://stackoverflow.com/questions/3504760/sitecore-system-security-cryptography-cryptographicexception – tHARA_sOFT Aug 20 '12 at 08:32
  • Which line throws the exception? Is it the line that sets the Crendentials? If so I guess the problem is related to the Password property. Also, please show your config. The empty ctor uses the mailSettings config element. – Ikaso Nov 02 '13 at 08:54

1 Answers1

1

Check your project settings and make sure you have checked NTLM Authentication:

enter image description here

Arash N
  • 324
  • 1
  • 2
  • 10