veena hosur veena hosur - 9 days ago 7
ASP.NET (C#) Question

why getting SMTP error in asp.net

I have login page.login is working fine but when trying to create new user, I'm getting


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


here is code which I am using to send mail

public void SendConfirmationAfterRegister(String EmailID, String UserName)
{
MailMessage mailMsg = new MailMessage();

String BodyMsg = UserName + ", \r\n\nWe have recieved your request to become a user of our site. Upon review, we will send you verification for site access.\r\n\n" +
"Thank you, \r\n\nMuda Admin";
try
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["AdminEmail"].ToString(), ConfigurationManager.AppSettings["Pwd"].ToString()),
EnableSsl = true
};

mailMsg.IsBodyHtml = true;
client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), EmailID, "Received Your Request", BodyMsg);

client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), "mymailId", "User Needs Access", EmailID + " looking for access the xyz Network Site.");
}
catch (Exception ex) { throw new Exception(ex.Message); }
}


can any one what is wrong

Answer

Try this:

public void SendConfirmationAfterRegister(String EmailID, String UserName)
{
    MailMessage mailMsg = new MailMessage();

    String BodyMsg = UserName + ", \r\n\nWe have received your request to become a user of our site.  Upon review, we will send you verification for site access.\r\n\n" +
        "Thank you, \r\n\nMuda Admin";
    try
    {
        using (var client = new SmtpClient("smtp.gmail.com", 587))
        {
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["AdminEmail"].ToString(), ConfigurationManager.AppSettings["Pwd"].ToString());
            client.EnableSsl = true;

            mailMsg.IsBodyHtml = true;
            client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), EmailID, "Received Your Request", BodyMsg);

            client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), "mymailId", "User Needs Access", EmailID + " looking for access the xyz Network Site.");
        }
    }
    catch (Exception ex) { throw new Exception(ex.Message); }
}

You need to set UseDefaultCredentials to false.

Note: You MUST set UseDefaultCredentials to false before setting the Credentials property.