Home > DeveloperSection > Forums > Email not being sent from MVC 3 with C# using gmail a/c
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    March-02-2013 1:49 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 1448  View(s)
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



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    March-02-2013 7:57 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick