Blog Article:

How To Resend Failed Emails With Kentico

by Piyush Kothari on June 15, 2017

Introduction

How many times have you logged into Kentico after the weekend and found tons of failed emails in the queue and unhappy customers waiting for them? Email Queue works great, but if an email is not sent due to an issue on the side of your server or the email server, it just sits doing absolutely nothing and waits for you to manually re-send it.

The fix for this issue is so simple that anyone can do it. Actually, it borders on simplistic. You do not need to have advanced programming knowledge to understand and follow the instructions that we will provide in this article.

Instructions

Our task basically has two parts. One checks that the conditions for calling the function to resend the emails are met, and if they are, the second part calls the function. First, we will create a scheduled task in the App_Code directory of your Kentico project. Then, we will name it ResendFailedEmails. Afterward, we will call the following function:

EmailHelper.Queue.SendAllFailed();

However, there is a catch. Email Queue sends emails in batches, but it can only process one batch at a time. So, the task needs to check if Email Queue is working on a bundle before calling the function, and if it is, delay the execution of the task by a few minutes.

if (EmailHelper.Queue.SendingInProgess)
{
    task.TaskNextRunTime = DateTime.Now.AddMinutes(5);
    result = "Retry in 5 mins";
}

When you’re done, your task should look like this:

[assembly: RegisterCustomClass("ResendFailedEmails", typeof(ResendFailedEmails))]
public class ResendFailedEmails : ITask
{
    public string Execute(TaskInfo task)
    {
        string result = String.Empty;

        try
        {
            if (EmailHelper.Queue.SendingInProgess)
            {
                task.TaskNextRunTime = DateTime.Now.AddMinutes(5);
                result = "Retry in 5 mins";
            }
            else
            {
                EmailHelper.Queue.SendAllFailed();
                result = "Emails successfully sent";
            }

        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("ResendFailedEmails", "E", ex);
            return ex.Message;
        }

        return result;
    }
}

Now, register the task from the Kentico administration interface and set it to run every couple hours or as frequently as you need. 

Conclusion

This is an easy way to resend failed emails with just a few lines of code. Please leave your thoughts and comments below, and tell us if you have a different approach to solve this problem.

Piyush Kothari

Piyush is a Kentico Certified Developer and adept with ASP.NET, C#, and Javascript . His experience developing within the Kentico platform since early versions and his keen business sense make him an invaluable asset to the Tusk team.