Recursion Parameter Recursion Parameter - 1 month ago 4
C# Question

Can someone show me right way to send SMTP email in C# code for ASP.NET page

I tried this SMTP example. When I use Yahoo's server 'smtp.mail.yahoo.com' with port number:465 it sends timeout exception (tested with breakpoint on catch block, because page loading wouldn't stop) and after some time again throws same exception. Now that I used google's server with 587 port, it threw new 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


Note that I didn't have 2 step verification enabled for my google account.

MailMessage m = new MailMessage();

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

NetworkCredential nc = new NetworkCredential();
nc.UserName = "test"
nc.Password = "password";

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = nc;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(m);
L.Text = "<br/>Email sent<br/>";
}
catch (Exception ex)
{
L.Text = ex.Message;
if (ex.InnerException != null)
L.Text = L.Text + " : " + ex.InnerException.Message;
}


Also what does this marked answer state about Production server in this question and how do i use it (if it works)?

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

Answer

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.

Comments