Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Core 2.1 Email Confirmation

Have been searching for quite some time but haven't found any source of how to set up an Account/Email confirmation in SMTP form, instead of any other mode like using SendGrid/MailKit, for an ASP Core 2.1 project using Razor Class Library.

Any suggestion in this regard? How to use IdentityUser in this regard? Is it necessary to scaffold the Identity first? Please see if any of you experts can help in this regard.

like image 780
Faraz Ahmed Qureshi Avatar asked Jun 28 '18 09:06

Faraz Ahmed Qureshi


1 Answers

Using SendGrid and other services is recommended in production since these services are setup to scale properly and can handle sending millions of emails at a time.

However, I do appreciate that it can be nice to setup an SMTP email when running your app in dev.

So, for the most part you can follow the docs on setting up email confirmation. What you need to change is the EmailSender implementation to use your SMTP server.

using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.UI.Services;

namespace YourApp
{
    public class DevEmailSender : IEmailSender
    {
        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            var client = new SmtpClient("yoursmtpserver") {
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("yourusername", "yourpassword")
            };
            var mailMessage = new MailMessage {
                From = new MailAddress("[email protected]")
            };
            mailMessage.To.Add(email);
            mailMessage.Subject = subject;
            mailMessage.Body = htmlMessage;
            return client.SendMailAsync(mailMessage);
        }
    }
}

Then you just need to configure this as a services in ConfigureServices in Startup.cs:

services.AddTransient<IEmailSender, DevEmailSender>();

Setting up an SMTP server is out of scope here, but if you have gmail for instance, you can follow this blog post on how to do so. Again, bear in mind that this is not a production strategy and actually opens your gmail account up to security vulnerabilities, which google will highlight to you when you set it up. However, if you use a throw away account, this can be a quick and dirty solution to getting email confirmation going with ASP.NET Core Identity.

like image 198
marcusturewicz Avatar answered Sep 28 '22 03:09

marcusturewicz