Search code examples
c#.netemailsmtpgmail

Sending Email using live/gmail smtp


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)
    {
        try
        {
            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)
                {
                    mailMessage.Attachments.Add(attachment);
                }
            }

            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587; //465
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "passsword");
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMessage);

            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

What am I doing wrong and how do I use gmail to send email.


Solution

  • You haven't set UseDefaultCredentials to 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.