Replies: 2 comments
-
One way to do this would be to add DI for a fluent email service like MailKitSimplified and put the configuration in appsettings.json. |
Beta Was this translation helpful? Give feedback.
-
you could use SendGrid API: https://sendgrid.com/en-us/solutions/email-api and implement Microsoft.AspNetCore.Identity.IEmailSender in the Infrastructure project.
public class SendGridSettings
{
public string ApiKey { get; set; }
public string FromEmail { get; set; }
public string FromName { get; set; }
}
services.Configure<SendGridSettings>(configuration.GetSection("SendGrid"));
"SendGrid": {
"ApiKey": "your-sendgrid-api-key",
"FromEmail": "[email protected]",
"FromName": "YourApp"
}
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace YourNamespace.Infrastructure.Identity
{
public class EmailSender : IEmailSender<ApplicationUser>
{
private readonly IConfiguration _configuration;
private readonly ILogger<EmailSender> _logger;
public EmailSender(IConfiguration configuration, ILogger<EmailSender> logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task SendEmailAsync(ApplicationUser user, string subject, string htmlMessage)
{
try
{
var apiKey = _configuration["SendGrid:ApiKey"];
var fromEmail = _configuration["SendGrid:FromEmail"];
var fromName = _configuration["SendGrid:FromName"];
var client = new SendGridClient(apiKey);
var from = new EmailAddress(fromEmail, fromName);
var to = new EmailAddress(user.Email);
var msg = MailHelper.CreateSingleEmail(from, to, subject, htmlMessage, htmlMessage);
var response = await client.SendEmailAsync(msg);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("Failed to send email to {Email}: {StatusCode}", user.Email, response.StatusCode);
throw new Exception($"Email sending failed with status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred while sending email to {Email}", user.Email);
}
}
}
}
services.AddScoped<IEmailSender<ApplicationUser>, EmailSender>(); With this setup, your application can use IEmailSender to send emails, including email confirmation and password reset functionalities. |
Beta Was this translation helpful? Give feedback.
-
hi Jason, hope you're doing great!, first of all, thanks for this template looks awesome!.
How can we configure the email service? so that we can use it when sending emails to the users like resendEmailConfirmation etc.
thanks in advance.
Beta Was this translation helpful? Give feedback.
All reactions