Setup SendGrid Account
- Setup account at https://sendgrid.com/
- Get API key.
- NuGet and install SendGrid to app.
Blazor WebAssembly Setup
Note:
- Add to “Server” project, not “Client” project.
- Need to setup user secrete for the application first.
Add “SendGridUser” and “SendGridKey” user secrete to Server project.
PM> dotnet user-secrets init --project "C:\MyApp\Server"
PM> dotnet user-secrets set SendGridUser test@test.com --project "C:\MyApp\Server"
PM> dotnet user-secrets set SendGridKey xxxxxxxxxxxxxxxxxxxxx --project "C:\MyApp\Server"
secrets.json
{
"SendGridUser": "test@test.com",
"SendGridKey": "xxxxxxxxxxxxxxxxxxxxx"
}
Add classes to Services folder
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;
AuthMessageSenderOptions.cs
public class AuthMessageSenderOptions
{
public string SendGridUser { get; set; }
public string SendGridKey { get; set; }
}
EmailSender.cs
public class EmailSender : IEmailSender
{
public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
public AuthMessageSenderOptions Options { get; } //set only via Secret Manager
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SendGridKey, subject, message, email);
}
public Task Execute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("test@test.com", Options.SendGridUser),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
// Disable click tracking.
// See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
msg.SetClickTracking(false, false);
return client.SendEmailAsync(msg);
}
Areas.Identity.Pages.Account.RegisterConfirmation page
DisplayConfirmAccountLink = false;
Startup.cs
using Microsoft.AspNetCore.Identity.UI.Services;
using MyApp.Server.Services;
public void ConfigureServices(IServiceCollection services)
{
// requires
// using Microsoft.AspNetCore.Identity.UI.Services;
// using CustomersdbPOS.Server.Services;
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
}
Comments