James Teare
James Teare

Reputation: 372

Ignoring invalid mail server certificates in C#

I am attempting to send an email, although an error message returned saying:

The remote certificate is invalid according to the validation procedure

My code is as follows:

   static void sendEmail()
        {
            var fromAddress = new MailAddress("xxxxxxxx@xxxxxxxx", "xxxxxxx");
            var toAddress = new MailAddress("xxxxxxxx@xxxxxxxx", "xxxxxxxx");
            const string fromPassword = "xxxxxxxxxxxx";
            const string subject = "xxxxxxxxxxxxxxxxxxxxx";

            var smtp = new SmtpClient
            {
                Host = "mailserver",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("username", fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = bodyglobal
            })
            {
                smtp.Send(message);
            }

        }

Upvotes: 1

Views: 3234

Answers (2)

Md Kamruzzaman Sarker
Md Kamruzzaman Sarker

Reputation: 2407

Sending email depends on how the SMTP server is configured.

According to gmail confiruged You need to remove this line of code

UseDefaultCredentials = false,

just comment this line and your message will be send.

 var smtp = new SmtpClient
        {
            Host = "mailserver",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            // do not use this command
           // UseDefaultCredentials = false,
            Credentials = new NetworkCredential("username", fromPassword)
        };

Microsoft suggest not to use defaultcredentials when possible. See this this

Upvotes: 0

javasocute
javasocute

Reputation: 648

try setting

 EnableSsl = false;

I had this issue a few weeks ago and this was the fix. If your program doesnt need/use SSL then a smtpexecption will fire with that error message.

Upvotes: 1

Related Questions