Search code examples
c#.netwebsmtpsmtpclient

Error in Sending Email via a SMTP Client


This may be very trivial for you but i just couldn't figure out why am i getting this error message when i run my code. I looked some of the relative questions on this same website for eg Sending email through Gmail SMTP server with C# but none of them was helpful. Anyone willing to help please? using different assemblies are also acceptable. so if anyone got a working solution that would be appreciated.

Error Message = The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

here is my code

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();      
message.From = new MailAddress("[email protected]");
message.To.Add("[email protected]");
message.Subject = "Hello";
message.Body = "Hello Bob ";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("MyGoogleMailAccount", 
                                               "mygooglemailpassword");

smtpClient.Send(message.From.ToString(), message.To.ToString(), 
                message.Subject, message.Body);   

Solution

  • I don't think there's anything wrong with your code other than the e-mail addresses. I used this code to successfully send an e-mail from gmail to my personal account (ran it in LINQPad, actually). Simply replace the 3 string values with valid values for your accounts and you should be good to go:

    MailMessage message = new System.Net.Mail.MailMessage(); 
    string fromEmail = "[email protected]";
    string fromPW = "mypw";
    string toEmail = "[email protected]";
    message.From = new MailAddress(fromEmail);
    message.To.Add(toEmail);
    message.Subject = "Hello";
    message.Body = "Hello Bob ";
    message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    
    using(SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
    {
        smtpClient.EnableSsl = true;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new NetworkCredential(fromEmail, fromPW);
    
        smtpClient.Send(message.From.ToString(), message.To.ToString(), 
                        message.Subject, message.Body);   
    }