Reputation: 4174
In ASP.NET, you configure email for Identity in IdentityConfig.cs in the App_Start folder, as per my own answer here.
ASP.NET Core Identity is now a library. And does not include this IdentityConfig.cs file by default. So how can I configure email sending, say, for Registration confirmation?
Upvotes: 7
Views: 18204
Reputation: 21656
You could refer the following steps to send email using SMTP:
Create a EmailSender class, and contains the following method:
public interface IMyEmailSender
{
void SendEmail(string email, string subject, string HtmlMessage);
}
public class MyEmailSender : IMyEmailSender
{
public IConfiguration Configuration { get; }
public MyEmailSender(IConfiguration configuration)
{
Configuration = configuration;
}
public void SendEmail(string email, string subject, string HtmlMessage)
{
using (MailMessage mm = new MailMessage(Configuration["NetMail:sender"], email))
{
mm.Subject = subject;
string body = HtmlMessage;
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = Configuration["NetMail:smtpHost"];
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(Configuration["NetMail:sender"], Configuration["NetMail:senderpassword"]);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
Store the SMTP configuration information in the appsettings.json
"NetMail": { "smtpHost": "smtp.live.com", "sender": "sender email", "senderpassword": "Password" },
Register the EmailSernder in the ConfigureServices method in Startup.cs file.
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddTransient<IMyEmailSender, MyEmailSender>();
In the Register.cs file, after creating user, you could use UserManager to get the EmailConfirmationToken, and get the callbackurl, then, call the SendEmail() method to send email.
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
_myEmailSender.SendEmail(Input.Email, "Confirm your Email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
After that, you will receive a email like this:
After clicking the link, it will redirect to the Confirm Email page, then, check the database, the EmailConfirmed was changed to True
.
Reference: Account confirmation and password recovery in ASP.NET Core
Upvotes: 4
Reputation: 4174
ASP.NET Core 2 relies a lot on dependency injection. Identity Library's RegisterModel (as well as the other email-dependant models) has the following field:
private readonly IEmailSender _emailSender;
All you have to do is use Startup.cs ConfigureServices method to inject an IEmailSender implemented by yourself:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IEmailSender, EmailSender>();
}
You may define this EmailSender class inside a folder named Services in your project:
And a possible implementation would be:
using Microsoft.AspNetCore.Identity.UI.Services;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace YourProject.Services
{
public class EmailSender : IEmailSender
{
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
SmtpClient client = new SmtpClient
{
Port = 587,
Host = "smtp.gmail.com", //or another email sender provider
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("your email sender", "password")
};
return client.SendMailAsync("your email sender", email, subject, htmlMessage);
}
}
}
Upvotes: 16