Karthik G
Karthik G

Reputation: 1262

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.

Upvotes: 0

Views: 943

Answers (2)

user1666620
user1666620

Reputation: 4808

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.

Upvotes: 3

Raktim Biswas
Raktim Biswas

Reputation: 4087

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

Secure App

Upvotes: 2

Related Questions