Engineering · Common · Sitecore

Programmatically resume paused emails in Sitecore EXM

When an email campaign is dispatched, it moves through a number of states (Draft, Queuing, Sending, and Sent). If an error occurs during dispatch and the IIS server is interrupted, the email campaign is not moved to the Sent state. Instead, it is moved to the Paused state and the user must resume the email campaign manually.

As an alternative, we will create a scheduled task that scans all the emails, returns a list of paused email campaigns and resumes those dispatches.

First, we create a task to get a list of paused emails. We create a class called “ResumePausedEmail”, which needs “EcmDataProvider” and “ManagerRootService”. Initialise both in the constructor:

private readonly EcmDataProvider _dataProvider;
private readonly IManagerRootService _managerRootService;

        public ResumePausedEmail() : this(ServiceLocator.ServiceProvider.GetService<EcmDataProvider>(), ServiceLocator.ServiceProvider.GetService<IManagerRootService>())
        {
        }

internal ResumePausedEmail([NotNull] EcmDataProvider dataProvider, [NotNull] IManagerRootService managerRootService)
        {
            _dataProvider = dataProvider;
            _managerRootService = managerRootService;
        }

The following code will return ManagerRoots:

 List<ManagerRoot> managerRoots = _managerRootService.GetManagerRoots();

The following code will return campaigns with a “Paused” or “Queuing” status.

var options = new CampaignSearchOptions
{
    ManagerRootId = managerRoot.Id,
    StatusInclude = new[]
        {
           EcmTexts.Paused,
           EcmTexts.Queuing
        },
    Page = new DataPage
       {
           Index = 0,
           Size = 10
       }
 };
CampaignSearchResults campaigns = _dataProvider.SearchCampaigns(options);

To resume emails, we will need “SendingManagerFactory” and “ExmCampaignService”. Then we loop through the email campaigns and resume them one by one.

 var sendingManagerFactory = ServiceLocator.ServiceProvider.GetService<ISendingManagerFactory>();
                var campaignService = ServiceLocator.ServiceProvider.GetService<IExmCampaignService>();

                foreach (EmailCampaignsData campaign in campaigns)
                {
                    MessageItem emailCampaign = campaignService.GetMessageItem(campaign.MessageId);

                    ISendingManager sendingManager = sendingManagerFactory.GetAsyncSendingManager(emailCampaign);

                    sendingManager.ResumeMessageSending();
                }

Now we need to create a scheduled task. This has two parts: creating a Command and creating a Schedule. Tasks are located in “/sitecore/system/Tasks”.

Create a command that calls the task we created above.

In the Schedule, first select the command we just created. Then define the start date and time, end date and time, and interval.

Now the scheduler is ready to resume paused and queuing emails.

Thanks
Munir