How to Send Emails in Sitecore Content Hub

Vasiliy Fomichev

In Content Hub, How To Posted

The post provides a reusable Sitecore Content Hub script snippet for notifying members of a Content Managers group. This script can be used to notify Sitecore Content Hub users of a given event using triggers calling a script-type action. The script can be used as-is, it sends an email to members of the “Content Managers” user group when a new asset got approved.

Sitecore Content Hub Email Templates

The script uses the concept of Sitecore Content Hub email templates, which makes it easy to update email format and content without updating the script to a certain point. Using email templates is recommended, as it increases the flexibility and promotes reusability, where the same template can be reused in multiple scenarios. Ultimately, using email templates reduces the cost of maintenance. To read more about email templates in Sitecore Content Hub, please reference the Email Templates documentation on the Sitecore documentation website.

The script below makes use of email template variables that can be specified in the email copy surrounded by double curly brackets, for instance, {{AssetUrl}}. They should also be registered with the template and values for each variable should be passed on to the template in the .Variables property.

Content Hub Notification Email Script

The following script goes through the following high-level steps:

  1. Check if a given named email template exists, and create a simple empty one, if it doesn’t
  2. Retrieve the Content Managers group
  3. Retrieve all usernames from the group
  4. Send notification email using the email template and retrieved usernames

 

using Stylelabs.M.Base.Querying;
using Stylelabs.M.Sdk.Contracts.Base;
using Stylelabs.M.Sdk.Contracts.Notifications;
using Stylelabs.M.Sdk.Models.Notifications;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
const string emailTemplatename = "Asset Acceptance Notification";

SendEmailAsync();

public async Task SendEmailAsync()
{
var rejectionTemplate = await MClient.Notifications.GetMailTemplateAsync(emailTemplatename);
if (rejectionTemplate == null)
{
await CreateEmailTemaplateAsync();
rejectionTemplate = await MClient.Notifications.GetMailTemplateAsync(emailTemplatename);
}
var groupId = MClient.Users.GetUserGroupAsync("Content Managers").Result.Id;
var query = Query.CreateQuery(entities =>
from e in entities
where e.DefinitionName == "User"
select e);
var users = MClient.Querying.QueryAsync(query, new EntityLoadConfiguration { RelationLoadOption = RelationLoadOption.All}).Result;

var groupUsers = new List<IEntity>();
foreach(var user in users.Items)
{    
    var groupRelation = user.GetRelation<IChildToManyParentsRelation>("UserGroupToUser");
    if (groupRelation.Parents.Contains(group.Id ?? 0)) // nullable ID, provide fallback
    {
        groupUsers.Add(user);
     }
}
            
var userNames = MClient.Users.GetUsernamesAsync(groupUsers.Select(i => i.Id ?? 0).ToList()).Result?.Select(i => i.Value).ToList();

var notificationRequest = new MailRequestByUsername
{
MailTemplateName = emailTemplatename,
Recipients = userNames
};
var entityModified = Context.Target as IEntity;
notificationRequest.Variables.Add("AssetUrl", "https://somedomain.stylelabsdemo.com/en-us/asset/"+entityModified.Id);
await MClient.Notifications.SendEmailNotificationAsync(notificationRequest);
}
public async Task CreateEmailTemaplateAsync()
{
var enUs = CultureInfo.GetCultureInfo("en-US");
var template = await MClient.EntityFactory.CreateAsync(Stylelabs.M.Sdk.Constants.MailTemplate.DefinitionName) as IMailTemplate;
template.Name = emailTemplatename;
template.SetSubject(enUs, "Asset Approved");
template.SetBody(enUs, "Hello, the following asset got approved: {{AssetUrl}}");
template.SetDescription(enUs, emailTemplatename);
template.SetTemplateVariables(new[] {
new TemplateVariable
{
Name = "AssetUrl",
VariableType = TemplateVariableType.String
}
});
await MClient.Entities.SaveAsync(template);
}

 

 

Quick Tip

When creating scripts, make sure to avoid blocking the application by running heavy processing in your In Process Action scripts (read more about Content Hub script types). Use background scripts, or offload these operations to other systems, like a combination of an Azure service bus and a function or a Logic App.

Summary
How to Send Emails in Sitecore Content hub Programmatically
Article Name
How to Send Emails in Sitecore Content hub Programmatically
Description
This short post provides an example of a script that retrieves users of a given group and sends them an email using Sitecore Content Hub email templates.
Author