'Email sending working in localhost but when not in published web on server in ASP.NET MVC I am using 587 port

I am trying to send mail from Gmail and it's sent successfully from localhost, but when I publish the website to the server, it didn't send it from there.

Any help?

This is my code - ASP.NET Core 5.0 using for the API project and this is the code how can I resolve this issue please help me as soon as possible thanks in advance

[HttpPost , ValidateAntiForgeryToken]
[Route("Email/Post")]
public bool? Post([FromBody] ModEmail l_ModEmail)
{
    try
    {
        string l_Mail_From = "[email protected]";
        string l_Email_Password = "password";

        // Create Mail Message Object
        MailMessage l_MailMessage = new MailMessage(l_Mail_From,l_ModEmail.Pr_EmailTo, 
        l_ModEmail.Pr_Subject, l_ModEmail.Pr_Body);

        l_MailMessage.IsBodyHtml = true;

        // Create SmtpClient class to Send Message             
        SmtpClient l_SmtpClient = new SmtpClient();

        // Here you specify your smtp host address such as smtp.myserver.com
        l_SmtpClient.Host = "smtp.gmail.com";
        l_SmtpClient.Port = 587;
        l_SmtpClient.EnableSsl = true;

        // Specify that you don't want to use default credentials
        l_SmtpClient.UseDefaultCredentials = false;

        // Create user credentials by using NetworkCredential class 
        NetworkCredential l_NetworkCredential = new NetworkCredential();
        l_NetworkCredential.UserName = l_Mail_From;
        l_NetworkCredential.Password = l_Email_Password;
        l_SmtpClient.Credentials = l_NetworkCredential;
        l_SmtpClient.Send(l_MailMessage);

        return true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return null;
    }
}


Solution 1:[1]

It is related to Google Mail service. In your code, the mail host is smtp.gmail.com.

From May 30, 2022, ??Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password. For more information, see: https://support.google.com/accounts/answer/6010255.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mustafa Bazghandi