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)
3: String ListName = "TestList";
5: SPUser oCurrUser = SPContext.Current.Web.CurrentUser;
6: String CurrUserEmail = oCurrUser.Email.ToString();
8: SPUserToken oSysToken = SPContext.Current.Web.Site.SystemAccount.UserToken;
9: using (SPSite oSite = new SPSite("http://team.contoso.com", oSysToken))
11: using (SPWeb oWeb = oSite.AllWebs)
13: oWeb.AllowUnsafeUpdates = true;
14: SPList oList = oWeb.Lists[ListName];
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;
23: oalert.EventType = SPEventType.All;
24: oalert.AlertFrequency = SPAlertFrequency.Immediate;
27: catch (Exception ex)
29: // exception handling logic
31: oWeb.AllowUnsafeUpdates = false;
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!