I am using C# to send email using SMTP and gmail server.
Below is the code I am using for sending email. I encounter a few errors i.e.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
public static bool SendEmail(string from, string to, string cc, string bcc, string subject, string body, bool isBodyHtml, List<Attachment> attachmentList)
var mailMessage = new MailMessage();
var smtpClient = new SmtpClient();
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(string.Join(",", to)));
if (cc != null && cc.Any())
mailMessage.CC.Add(new MailAddress(string.Join(",", cc)));
if (bcc != null && bcc.Any())
mailMessage.Bcc.Add(new MailAddress(string.Join(",", bcc)));
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
if (attachmentList != null)
foreach (var attachment in attachmentList)
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587; //465
smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "passsword");
smtpClient.EnableSsl = true;
catch (Exception ex)
What am I doing wrong and how do I use gmail to send email.
You haven't set
false, so despite the fact you have provided credentials, the application is still trying to use your windows credentials to log into the SMTP. Try the below:
smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "passsword");
UseDefaultCredentials needs to be set to
false before you set the new network credentials.
If you are sure that your Username and Password are correct and you are still getting the error then it means that Gmail has blocked your application.
Try turning it on from here Grant Access to Less Secure Apps