I have a .net core 2.2 app with identity package and email confirmation required for users who register. I was able to have this send successfully after configuring my gmail to "allow less secure apps" . Now I am receiving error :"The SMTP server requires
a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required " when new user registers. I have a class called emailsender that draws from appsettings.json file.
Emailsender.cs:
using Microsoft.Extensions.Options;
using RequireConfirmedEmail.Entities;
using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
///
namespace RequireConfirmedEmail.Services
{
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string htmlMessage);
}
public class EmailSender : IEmailSender
{
private readonly EmailSettings _emailSettings;
public EmailSender(IOptions<EmailSettings> emailSettings)
{
_emailSettings = emailSettings.Value;
}
public Task SendEmailAsync(string email, string subject, string message)
{
try
{
// Credentials
var credentials = new NetworkCredential(_emailSettings.Sender, _emailSettings.Password);
///
// Mail message
var mail = new MailMessage()
{
From = new MailAddress(_emailSettings.Sender, _emailSettings.SenderName),
Subject = subject,
Body = message,
IsBodyHtml = true
};
mail.To.Add(new MailAddress(email));
// Smtp client
var client = new SmtpClient()
{
Port = _emailSettings.MailPort,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = _emailSettings.MailServer,
EnableSsl = true,
Credentials = credentials
};
// Send it...
client.Send(mail);
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}
return Task.CompletedTask;
}
}
}
====================appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=111.111.111.11;initial catalog=mydb;persist security info=True;user id=myusername;password=yyy;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"EmailSettings": {
"MailServer": "smtp.gmail.com",
"MailPort": 587,
"SenderName": "My Company",
"Sender": "mymail@gmail.com",
"Password": "zzz"
}
}
My gmail is configured for "allow less secure apps" , takes 587 for port via ssl
??
thanks in advance
Ned