Daniel Brown

Daniel Brown

  • NA
  • 21
  • 1.5k

Identity using SendGrid v3 to send transactional template

Dec 4 2017 10:25 AM

I'm new to asp.net mvc Identity and SendGrid but would really like to use the functionality of both of them.

I would like to let the user sign up using identity registration form and then use SendGrid v3 to send a template (built in my SendGrid account) as the account registration confirmation email. I've created a Transactional template and have an Api Key.

I have enabled email confirmation in identity:

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);                 await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("Index", "Home");

I have then set up my sendGrid apiKey and account credentials in the app settings of my web.config so I can use them in my code.

<appSettings> <add key="SendGridUsername" value="xxxxxxx" /> <add key="SendGridPassword" value="xxxxxxx" /> <add key="SendGridApiKey" value="xxxxxxxxxxxxxxxxxxxxxxxx" /> </appSettings>

I have added this to my EmailService in the IdentityConfig.cs but i'm stuck on where to go from here:

public class EmailService : IIdentityMessageService { public async Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email.  var apiKey = WebConfigurationManager.AppSettings["SendGridApiKey"]; var client = new SendGridClient(apiKey); var from = new EmailAddress("[email protected]", "Me"); var subject = message.Subject; var to = new EmailAddress(message.Destination); var email = MailHelper.CreateSingleEmail(from, to, subject, "", message.Body);         await client.SendEmailAsync(email); } }

I've also read the following but cannot understand where to implement it:

https://sendgrid.com/docs/API_Reference/Web_API_v3/Transactional_Templates/smtpapi.html

{ "filters": { "templates": { "settings": { "enable": 1, "template_id": "5997fcf6-2b9f-484d-acd5-7e9a99f0dc1f" } } } }

Any help on this would be awesome as i'm just not sure where to go from here.

Thanks