Introducing SendGridForEpi

Open sourced packages that helps you sending mail from Episerver using SendGrid's API and transactional templates.

I'm fairly certain most readers are familiar with SendGrid but I suspect most of you are just using their regular SMTP interface to send e-mails. This would be the typical setup when running Episerver on Azure or DXC Service.

If you have access to the SendGrid app it's very powerful to instead use the transactional templates and post mails through their REST API. This allows you to send to multiple recipients in one remote call and SendGrid will help you with the delivery timing to avoid being blacklisted. It's also very easy to hook up your own subdomain names for template images and click tracking; features that are unavailable when sending by SMTP.

Within a transactional template ID you also have the option switch between different template versions and of course you work with substitutions to personalize.

List of templates

SendGrid's template editor is pretty decent as well and you can choose to have your own substitution variable syntax. You have the option to post a complete body or smaller more focused variables as part of a Personalization object.

Pink template version

My SendGridForEpi package will help you by storing new Mail objects in a SQL Server table which later is processed by a Scheduled Job that does the actual posting to SendGrid's REST API. Your code could look something like this:

var mail = new Mail
{
    From = new Email("noreply@krompaco.nu"),
    TemplateId = "cf6d9ac4-****-480b-a95a-77921d060261"
};

mail.AddPersonalization(
    new Personalization()
    {
        Tos = new List<Email>
                {
                    new Email("somedude@krompaco.nu")
                },
        Substitutions = new Dictionary<string, string>
                {
                    { "{whoIs}", "Some Dude" },
                    { "{commentText}", "A <b>bold</b> comment" }
                }
    });

this.mailService.AddToQueue(new MailQueueItem
{
    Date = DateTime.UtcNow,
    Mail = mail
});

The included Scheduled Job:

The scheduled job

Benefits with this setup:

  • Nothing gets lost even when SendGrid can't be reached or your Mail object can't be posted. Latest error message and number of attempts is kept on the item.
  • Should be faster and more reliable than a HTTP or SMTP call in your user flow.
  • Completed items are archived to log table which can be used for statistics.

The repo README at Github should have all you need to get started and try it out. Please check the code and hit me with some pointers!

Published and tagged with these categories: Episerver, ASP.NET