Search code examples
c#.netasp.net-mvcsmtpgmail

Smtp authentification required


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("[email protected]", "password");
                smtpClient.Timeout = 20000;
            }
            mailMessage.To.Add(model.Email);
            mailMessage.From = new MailAddress("[email protected]");
            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?


Solution

  • 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("[email protected]", "password");
    

    Also, gmail doesn't allow impersonation, so

    mailMessage.From = new MailAddress("[email protected]");
    

    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.