A case of custom email templates not used when alerts are created from code in SharePoint

Recently, I had a case where customer was creating SPAlert object using SharePoint object model code and things were not working out well.

What seem to happen was that whenever the condition that warrants alert trigger is met (e.g., an item is changed in a list), the alert email that was sent out was not the custom alert email template customer had setup but it was the out of the box email template.

The customer had created a custom alert template by following How to create a custom e-mail alert handler in Microsoft Office SharePoint Server article.

After investigation we found that the code they were originally using did not have SPAlert.AlertTemplate property assigned with the correct value.  Once we provided the correct alert template to this property, the alert that was created through SharePoint object model code recognized the custom email template and used that template in the emails that were sent when the alert trigger condition is met.

Below is the sample code.

    1: void bElevated_Click(object Sender, EventArgs e)
    2: {
    3:      String ListName = "TestList";
    4:  
    5:      SPUser oCurrUser = SPContext.Current.Web.CurrentUser;
    6:      String CurrUserEmail = oCurrUser.Email.ToString();
    7:  
    8:      SPUserToken oSysToken = SPContext.Current.Web.Site.SystemAccount.UserToken;
    9:      using (SPSite oSite = new SPSite("https://team.contoso.com", oSysToken))
   10:      {
   11:           using (SPWeb oWeb = oSite.AllWebs[0])
   12:           {
   13:                oWeb.AllowUnsafeUpdates = true;
   14:                SPList oList = oWeb.Lists[ListName];
   15:  
   16:                try
   17:                {
   18:                     SPUser ospuser = oWeb.SiteUsers.GetByEmail(CurrUserEmail);
   19:                     SPAlert oalert = ospuser.Alerts.Add();
   20:                     oalert.AlertType = SPAlertType.Item;
   21:                     oalert.AlertTemplate = oList.AlertTemplate;
   22:                     oalert.Item = oList.Items[0];
   23:                     oalert.EventType = SPEventType.All;
   24:                     oalert.AlertFrequency = SPAlertFrequency.Immediate;
   25:                     oalert.Update();
   26:                }
   27:                catch (Exception ex)
   28:                {
   29:                     // exception handling logic
   30:                }
   31:                oWeb.AllowUnsafeUpdates = false;
   32:           }
   33:      }
   34: }

Line number 21 above was the statement missing in the original code.  We need to specify the SPAlert.AlertTemplate property in order to get alert emails sent out using the custom email template.

Hope this helps!

Cross post from https://blogs.msdn.com/sridhara