0
votes

I was new to SMTP client in C#. So I decided to test it with my credentials. I built an ASP.NET Web forms application that has a Contact Us page on which I am trying to send an email to whoever person fills the form.

I tried sample code after going through this article - https://www.c-sharpcorner.com/UploadFile/87b416/sending-a-simple-email-using-smtpclient-in-C-Sharp/

I have one account in Yahoo so I used its SMTP domain "smtp.mail.yahoo.com" with port number: 465, then my app always threw Timeout exception. So I decided to try with Google's server "smtp.gmail.com" with "587" port and now it raised different exception with message:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

I don't understand what are the prerequisites for working with SMTP on secure servers like Google and Yahoo. Please someone explain.

Also note that I didn't have 2 step verification enabled for my Google account, just to make it clear since some questions on SO have mentioned that this might be the problem.

I also read this question but I am testing directly on my machine - Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

In case if it helps, here is the sample code:

try
{
    MailMessage m = new MailMessage();

    m.From = new MailAddress("dummy123@gmail.com");
    m.To.Add(new MailAddress("dummyreceiver123@gmail.com"));
    m.Subject = TBSub.Text;
    m.Body = TBBody.Text;
    m.IsBodyHtml = true;

    NetworkCredential nc = new NetworkCredential();
    nc.UserName = "dummy123"
    nc.Password = "dummy@123";

    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.Credentials = nc;
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Send(m);
}
catch (Exception ex)
{
    //Log this error
}
1
Have you tried adding smtp.UseDefaultCredentials = false; when you assign your credentials object?NinjaMid76
Thanks for commenting @NinjaMid76. I added that statement yet it gives 'SMTP Authentication error exceptionAkshay Raut

1 Answers

0
votes

I just tested out your code it works fine you just need to modify this section:

nc.UserName = "test"
nc.Password = "password";

This has to be a valid gmail or google app email along with the password for the smtp connection to work properly. I would recommend that you put in your own for testing purposes, and then modify this to have your email as well:

m.From = new MailAddress("yourEmail@gmail.com");
m.To.Add(new MailAddress("yourEmail@gmail.com"));

Just so that you can validate that your message is being passed from your function.