Abdul Ali
Abdul Ali

Reputation: 1937

Email not being sent from C# using gmail a/c

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."

The email and password are same as used for Login..

Following is the complete 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();

Any help appreciated :) -- Kind regards,

Upvotes: 0

Views: 380

Answers (1)

netblognet
netblognet

Reputation: 2016

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.

Upvotes: 2

Related Questions