-7

I have an asp.net mvc application, and I'd like to send an email :

 MailMessage mailMessage = new MailMessage();
            var smtpClient = new  SmtpClient();
            {
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtpClient.Credentials = new NetworkCredential("myemail@gmail.com", "password");
                smtpClient.Timeout = 20000;
            }
            mailMessage.To.Add(model.Email);
            mailMessage.From = new MailAddress("support@team.com");
            mailMessage.Subject = "Modification de mot de passe";
            mailMessage.Body = "Vous avez modifié votre mot de passe de votre Compte ";
            mailMessage.Body += Environment.NewLine;
            mailMessage.Body += "le nouveau mot de passe est : ";
            mailMessage.Body += newPassword; 
            smtpClient.Send(mailMessage); 

I get this exception :

La réponse du serveur était : 5.5.1 Authentication Required.

in last line of code.

I need to know what is the reason of this problem? How can I resolve it?

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191

2 Answers2

2

You need to tell the SMTP client that you will not be using your windows credentials to access the SMTP, so add

smtpClient.UseDefaultCredentials = false;

above this line of code

smtpClient.Credentials = new NetworkCredential("myemail@gmail.com", "password");

Also, gmail doesn't allow impersonation, so

mailMessage.From = new MailAddress("support@team.com");

will have no effect - the emails will still appear to be sent from the email account you are accessing.

Also, make sure that the setting "allow less-secure applications" is set on your gmail account, and that 2-factor authentication is not enabled.

user1666620
  • 4,800
  • 18
  • 27
0

Have you SSL enabled on your account?

Depending on your Gmail account settings, you may get authentication errors within your app. If your Gmail account uses 2-Step-Verification, you should generate an App password to use for your mailer_password parameter. You should also ensure that you allow less secure apps to access your Gmail account.

ChrisRun
  • 993
  • 1
  • 10
  • 24