简体   繁体   中英

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 ie

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("username@email.com", "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.

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("username@email.com", "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

安全应用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM