Keyboard - Alpha Solutions

In this Alpha Solutions Tech Tip, we share a code for how to create new email templates using the Notifications API.

2.13.20

BY NIKET ASHESH

Sitecore Content Hub email is a handy tool for notifying users. Out of the box, you get quite a few pre-configured emails. Naturally, you can flexibly customize Content Hub email templates to align with your company’s branding.

Content Hub also allows you to add new email templates by leveraging the Notifications API.

My go-to method is to create a template using the SDK. Here is the code that has worked well for me:

CultureInfo enUs = CultureInfo.GetCultureInfo("en-US");

                IMailTemplate template = await
client.EntityFactory.CreateAsync("M.Mailing.Template") as IMailTemplate;
                template.Name = "Email Template Name";
                
                template.SetSubject(enUs, "Subject");
                template.SetBody(enUs, "Body with some variables <a
href=\"{{assetLink}}\">Link to {{fileName}}</a>"
);
                var fileNameVariable = new TemplateVariable
                {
                    Name = "fileName",
                    VariableType = TemplateVariableType.String
                };
                var assetLinkVariable = new TemplateVariable
                {
                    Name = "assetLink",
                    VariableType = TemplateVariableType.String
                };
                template.SetTemplateVariables(new[] { fileNameVariable, assetLinkVariable
});

                long entityId = await client.Entities.SaveAsync(template);
                var entity = await client.Entities.GetAsync(entityId);
                if (entity != null)
                {
                    var label = await
entity.GetPropertyAsync<ICultureSensitiveProperty>("M.Mailing.TemplateLabel");
                    label.SetValue(enUs, "Subject");
                    var description = await
entity.GetPropertyAsync<ICultureSensitiveProperty>("M.Mailing.TemplateDescription");
                    description.SetValue(enUs, "Subject");
                    await client.Entities.SaveAsync(entity);
                }