EMAIL NOT BEING SENT FROM MVC 3 WITH C# USING GMAIL A/C

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
 1765  View(s)
Ratings:
Rate this:

Hi Expert!

The email is not being sent from C# code using the gmail smtp settings. It is giving an error of "Server requires a Secure connection or the Client was not authenticated."

My code

MailMessage mail = new MailMessage("<from>","<to>");

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.Credentials = new NetworkCredential("<email>", "<password>");
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Timeout = 20000;
            client.UseDefaultCredentials = false;

            mail.Body = "Test email from C# Code";
            mail.Subject = "Test Email";

            Console.WriteLine("Attempting to Send Email");

            try {
                client.Send(mail);
                Console.WriteLine("Email sent... ");
            }
            catch (System.Net.Mail.SmtpFailedRecipientException ex) {
                Console.WriteLine("Could not send email to the mentioned recipient" + ex.Message);
            }
            catch (System.Net.Mail.SmtpException ex) {
                Console.WriteLine("Could not send Email..\n" + ex.Message + "\n" + ex.StackTrace);               
            }
            Console.ReadLine();

Thanks in advance

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Email not being sent from MVC 3 with C# using gmail a/c

    Hi Jayden!

    You have to swap the following lines.

    client.Credentials = new NetworkCredential("<email>", "<password>");
    client.UseDefaultCredentials = false;

    You have to set the UseDedaultCredentials property at first.

    client.UseDefaultCredentials = false;   
    client.Credentials = new NetworkCredential("<email>", "<password>");


    That's the way, it should work.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!