Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);   
like image 986
Sike12 Avatar asked Sep 24 '13 17:09

Sike12


1 Answers

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);   
}
like image 63
Pete Avatar answered Sep 21 '22 04:09

Pete