First create your interface
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string message);
}
Implement the interface
public class EmailSender : IEmailSender
{
private readonly EmailConfiguration _emailConfig;
public EmailSender(IOptions<EmailConfiguration> emailConfig)
{
_emailConfig = emailConfig.Value;
}
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_emailConfig.DisplayName, _emailConfig.From));
message.To.Add(MailboxAddress.Parse(email));
message.Subject = subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = htmlMessage
};
using var client = new SmtpClient();
try
{
await client.ConnectAsync(
_emailConfig.SmtpServer,
_emailConfig.Port,
true
//MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable
);
//client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync(
_emailConfig.UserName,
_emailConfig.Password);
await client.SendAsync(message);
}
finally
{
await client.DisconnectAsync(true);
client.Dispose();
}
}
}
Create a class named EmailConfiguration
public class EmailConfiguration
{
public string From { get; set; }
public string DisplayName { get; set; }
public string SmtpServer { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string DefaultSubjectPrefix { get; set; } = "Message";
}
In your appsettings.json
"EmailConfiguration": {
"From": "your email here",
"SmtpServer": "smtp.gmail.com",
"DisplayName": "Your app name",
"Port": 465,
"UserName": "the same email here",
"Password": "input your password",
"DefaultSubjectPrefix": "Message"
}
Packages
MailKit.Net.Smtp MimeKit
Register the service in your Program.cs
builder.Services.AddScoped<IEmailSender, EmailSender>();
No comments yet. Be the first to share your thoughts!