Hello,
There might be couple of reasons for the authentication error.
If you have enabled 2way authentication and trying to use the same account in smtp then you might get the error.
Follow this URL: https://support.google.com/mail/answer/7126229?hl=en
For your second question:
I use https://mailtrap.io/ in the development. This provides a fake smtp details and much easy to use.
Here is the code to send emails using SMTP with https://mailtrap.io/ server.
Here is a model class:
public class SMTPConfigModel
{
public string SenderAddress { get; set; }
public string SenderDisplayName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public bool EnableSSL { get; set; }
public bool UseDefaultCredentials { get; set; }
public bool IsBodyHTML { get; set; }
}
Here are the settings from mailtrap:
"SMTPConfig": {
"SenderAddress": "no-reply@myapp.com",
"SenderDisplayName": "My Application Team",
"UserName": "07xxxxxx2a3d3699",
"Password": "ce423xxxxxxxxf90a",
"Host": "smtp.mailtrap.io",
"Port":587,
"EnableSSL": true,
"UseDefaultCredentials": true,
"IsBodyHTML": true
}
And finally use the following method to send the email using SMTP:
private async Task SendEmail(UserEmailOptions userEmailOptions)
{
MailMessage mail = new MailMessage
{
Subject = userEmailOptions.Subject,
Body = userEmailOptions.Body,
From = new MailAddress(_smtpConfig.SenderAddress, _smtpConfig.SenderDisplayName),
IsBodyHtml = _smtpConfig.IsBodyHTML
};
foreach (var toEmail in userEmailOptions.ToEmails)
{
mail.To.Add(toEmail);
}
NetworkCredential networkCredential = new NetworkCredential(_smtpConfig.UserName, _smtpConfig.Password);
SmtpClient smtpClient = new SmtpClient
{
Host = _smtpConfig.Host,
Port = _smtpConfig.Port,
EnableSsl = _smtpConfig.EnableSSL,
UseDefaultCredentials = _smtpConfig.UseDefaultCredentials,
Credentials = networkCredential
};
mail.BodyEncoding = Encoding.Default;
await smtpClient.SendMailAsync(mail);
}
Here are some important links:
Create custom SMTP email service in asp.net core
Send email from asp.net core application using SMTP
Send dynamic data (placeholders) in email from asp.net core app
Code Repository on GitHub: https://github.com/webgentle/aspnet-core-mvc
Kindly accept this answer if this works for you.
Thank you.