none
I need to send alert from dynamic email address if a new item added in my List

    Question

  • Hello Guys,

    First of all i am sorry , i am posting here as i did not find WSS3.0 in list , so i am posting it in SP 2010, requirement  I have, to change sender address dynamically from a list alert, first of all i should tell you about platform i am using

    WSS 3.0, Exchange server for email , but it has support for anonymous email sending from it's local network ,

    I got some sample code :blogs.msdn.com/b/sharepointdeveloperdocs/archive/2007/12/14/how-to-customizing-alert-emails-using-ialertnotificationhandler.aspx

    i have done all these and for sending email i am using normal SMTP mail as i have to change sender address dynamically , who the user will post an item in list , mail will be send from his email address not from  the email, configured in central administration, I have followed full steps told there, except mail sending from System.Net.Mail, my problem is my dll is not working after following these steps , it is sending mail from default template.

    I found something blogs.syrinx.com/blogs/sharepoint/archive/2008/04/28/custom-alert-handlers-part-1-of-2.aspx 

    in "Attaching the Template" section

    Not sure what is telling here , i mean what extra i have to do :(

    here is my code

    -------------------------------------

    using System;

    using Microsoft.SharePoint;

    using System.Web;

    using Microsoft.SharePoint.Utilities;

    using System.Net.Mail;

    using System.Collections;

    namespace HandleEmailAlerts

    {

       class EmailNotifierHelper : IAlertNotifyHandler

       {

           #region IAlertNotifyHandler Members

           public bool OnNotification(SPAlertHandlerParams ahp)

           {

               string eventType = String.Empty;

               try

               {

                   SPSite site = new SPSite(ahp.siteUrl + ahp.webUrl);

                   SPWeb web = site.OpenWeb();

                   SPList list = web.Lists[ahp.a.ListID];

                   SPListItem item = list.GetItemById(ahp.eventData[0].itemId);

                   //ahp.headers.Add("from", submittedBy.Email);

                   string FullPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl + "/" + list.Title + "/" + item.Name);

                   string ListPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl + "/" + list.Title);

                   string webPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl);

                   string build = "";

                   SPUser spUser=null;

                   if (ahp.eventData[0].eventType == 1)

                   {

                       eventType = "Added";

                       spUser = (SPUser)item["Created By"];

                   }

                   else if (ahp.eventData[0].eventType == 2)

                   {

                       eventType = "Changed";

                       spUser = (SPUser)item["Modified by"];

                   }

                   else if (ahp.eventData[0].eventType == 3)

                   {

                       eventType = "Deleted";

                       spUser = (SPUser)item["Modified by"];

                   }

                   build = "</head>" + "<p><strong>" + item.Name.ToString() + "</strong> has been " + eventType + "</p>" + "<table style=\"width: 100%\" class=\"style2\"><tr><td style=\"width: 25%\" class=\"style1\">" + "<a href=" + webPath + "/_layouts/mysubs.aspx>Modify my Settings</a></td>" + "<td style=\"width: 25%\" class=\"style1\"> <a href=" + FullPath + ">View " + item.Name + "</a></td>" + "<td style=\"width: 25%\" class=\"style1\"><a href=" + ListPath + ">View " + list.Title + "</a></td>" + "        </tr></table>";

                   string subject = list.Title.ToString();

                   //SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), subject, build);

                   SendMail(subject, build, spUser.Email, ahp);

                   return false;

               }

               catch (System.Exception ex)

               {

                   return false;

               }

           }

           /// <summary>

           /// Send mail from SMTP

           /// </summary>

           /// <param name="subject"></param>

           /// <param name="body"></param>

           /// <param name="from"></param>

           /// <param name="ahp"></param>

           private void SendMail(string subject, string body, string from, SPAlertHandlerParams ahp)

           {

               try

               {

                   MailMessage mMessage = new MailMessage();

                   mMessage.Subject = subject;

                   mMessage.Body = body;

                   mMessage.From=new MailAddress(from);

                   mMessage.To.Add(ahp.headers["to"].ToString());

                   mMessage.IsBodyHtml = true;

                   mMessage.Priority = MailPriority.High;

                   SmtpClient mSmtpClient = new SmtpClient();

                   System.Net.NetworkCredential credential = new System.Net.NetworkCredential("spemail@myserver.com", "password");

                   mSmtpClient.Credentials = credential;

                   mSmtpClient.Host = "mail.haifire.com";

                   mSmtpClient.Port = 25;

                   mSmtpClient.Send(mMessage);

               }

               catch (Exception ex)

               {

               }

           }

           #endregion

       }

    }

    --------------------------------------------------------

    You may think

    System.Net.NetworkCredential("spemail@myserver.com", "password");

                   mSmtpClient.Credentials = credential;

    these are the cause of problem, i have removed that as my email server support anonymous mailing , but problem remain, mail is going through the default template and from address is default email address.

    I need urgent help as my client is waiting for long time and i have consulted with some people working on the domain but :(,

    Guy's, please help me to complete the Job,

    Thanks in advance

    Thanks and regards

    Tanmay Mandal

    Tuesday, October 30, 2012 7:18 AM

Answers

All replies

  • Hi Tanmay,

    Use SPUTILITY menthod.

    Sputility.sendemil("spweb",headers,body);

    You can resolve your issue by using sputility menthod.

    Thnaks & Regards

    Anil.R


    Regards Anil.R

    • Proposed as answer by Anil Kumar 03 Wednesday, October 31, 2012 6:26 AM
    • Unproposed as answer by Anil Kumar 03 Wednesday, October 31, 2012 6:27 AM
    Tuesday, October 30, 2012 9:25 AM
  • Anil Kumar 03, he is trying to send email changing the "From" dynamically, that's why he didn't use the SPUtility.SendEmail which is taking the email set in the central administration.

    Tanmay : in the link you provide, it is said that when you have deploy your custom handler, you need to attach it. he said that he create an stsadm extension.. well if you use it only one times, no nedd for that.

    He also precise that you can use an event receiver to attach it.

    So I think you have 2 options, create an event receiver or create a small application that use that code here

    SPAlertTemplateCollection ats = new SPAlertTemplateCollection((SPWebService)_siteCollection.WebApplication.Parent);
                _newTemplate = ats[_alertTemplateName];
    
                if (_newTemplate == null)
                {
                    // We did not find the specified Template.
                    throw new Exception("Failed to find template " + _alertTemplateName + "in the template collection.");
                }
                _list.AlertTemplate = _newTemplate;
                _list.Update();

    Hope this help.


    Best regards, Christopher.
    Blog | Mail
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.
    Why mark as answer?

    Tuesday, October 30, 2012 12:48 PM
    Answerer
  • Hello  Christopher and Anil,

    thanks for the reply, Anil  Christopher is right , i have no option to send mail using SPUtility, because it will do things through central admin email settings . you can find i have commented that code :)

     Christopher, thanks for the help , i am trying SP Feature now , found msdn.microsoft.com/en-us/magazine/cc163428.aspx in for WSS 3.0,

    Guys you know the requirements now and what i did and what is the result , so please post code , sample if you find over internet that can help me.

    thanks and regards

    Tanmay Mandal

    Wednesday, October 31, 2012 6:26 AM
  • Hello,

    I think this link can help you to create and understand how works a feature receiver : http://www.simple-talk.com/dotnet/.net-framework/how-to-create-features-for-windows-sharepoint-services-3.0/

    I found also this short one doing what you are doing : http://sharepointsolutionspro.blogspot.be/2009/01/customize-wss-alert-template.html


    Best regards, Christopher.
    Blog | Mail
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.
    Why mark as answer?

    Wednesday, October 31, 2012 7:45 AM
    Answerer
  • Hello Christopher,

    Thanks for the feedback, i have done some code there 

    ===========================================================

                                           

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    using System;
    using System.IO;
    using Microsoft.SharePoint.Utilities;

    namespace DZTFeature
    {
        public class DZTFeatureHandler : SPFeatureReceiver
        {
            public override void FeatureInstalled(SPFeatureReceiverProperties properties)
            { }
            public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\log.log", true))
                {
                    stw.WriteLine("Doing Activation \n");
                    try
                    {
                        string alertTemplate = "customalerttemplates.xml";
                        SPWebApplication WebApplication = (SPWebApplication)properties.Feature.Parent;
                        SPWebService _WebService = WebApplication.WebService;


                        SPAlertTemplateCollection ats = new SPAlertTemplateCollection(_WebService);
                        foreach(SPAlertTemplate spa in ats)
                        {
                            stw.WriteLine("Name :" + spa.Name + " Farm :" + spa.Farm + " DisplayName :" + spa.DisplayName + "\n\n");
                        }

                        ats.InitAlertTemplatesFromFile(SPUtility.GetGenericSetupPath("TEMPLATE\\XML") + "\\" + alertTemplate); 
                        SPAlertTemplate _newTemplate = ats[alertTemplate];

                        if (_newTemplate == null)
                        {
                            // We did not find the specified Template.
                            throw new Exception("Failed to find template " + alertTemplate + "in the template collection.");
                        }
                        using (SPSite spSite = WebApplication.Sites["Litigation"])
                        {
                            using (SPWeb sWeb = spSite.OpenWeb())
                            {
                                SPList sListAO = sWeb.Lists["Conflict Check Form"];
                                sListAO.AlertTemplate = _newTemplate;
                                sListAO.Update();
                                stw.WriteLine("ListUpdated!! \n");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        stw.WriteLine("Error  :::::: \n\n");
                        stw.WriteLine(ex.Message);
                    }
                }
            }

            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\log.log", true))
                {
                    stw.WriteLine("Doing FeatureDeactivating \n");
                    try
                    {
                        string alertTemplate = "alerttemplates.xml";
                        SPWebApplication WebApplication = (SPWebApplication)properties.Feature.Parent;
                        SPWebService _WebService = WebApplication.WebService;


                        SPAlertTemplateCollection ats = new SPAlertTemplateCollection(_WebService);
                        ats.InitAlertTemplatesFromFile(SPUtility.GetGenericSetupPath("TEMPLATE\\XML") + "\\" + alertTemplate); 
                        SPAlertTemplate _newTemplate = ats[alertTemplate];

                        if (_newTemplate == null)
                        {
                            // We did not find the specified Template.
                            throw new Exception("Failed to find template " + alertTemplate + "in the template collection.");
                        }
                        using (SPSite spSite = WebApplication.Sites["Litigation"])
                        {
                            using (SPWeb sWeb = spSite.OpenWeb())
                            {
                                SPList sListAO = sWeb.Lists["Conflict Check Form"];
                                sListAO.AlertTemplate = _newTemplate;
                                sListAO.Update();
                                stw.WriteLine("List Deactivated!! \n");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        stw.WriteLine("Error  :::::: \n\n");
                        stw.WriteLine(ex.Message);
                    }
                }
            }
            public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
            {
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\log.log", true))
                {
                    stw.WriteLine("Doing FeatureUninstalling \n");
                    try
                    {
                        string alertTemplate = "alerttemplates.xml";
                        SPWebApplication WebApplication = (SPWebApplication)properties.Feature.Parent;
                        SPWebService _WebService = WebApplication.WebService;


                        SPAlertTemplateCollection ats = new SPAlertTemplateCollection(_WebService);
                        ats.InitAlertTemplatesFromFile(SPUtility.GetGenericSetupPath("TEMPLATE\\XML") + "\\" + alertTemplate); 
                        SPAlertTemplate _newTemplate = ats[alertTemplate];

                        if (_newTemplate == null)
                        {
                            // We did not find the specified Template.
                            throw new Exception("Failed to find template " + alertTemplate + "in the template collection.");
                        }
                        using (SPSite spSite = WebApplication.Sites["Litigation"])
                        {
                            using (SPWeb sWeb = spSite.OpenWeb())
                            {
                                SPList sListAO = sWeb.Lists["Conflict Check Form"];
                                sListAO.AlertTemplate = _newTemplate;
                                sListAO.Update();
                                stw.WriteLine("List Deactivated in Uninstall!! \n");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        stw.WriteLine("Error  :::::: \n\n");
                        stw.WriteLine(ex.Message);
                    }
                }
            }
        }
    }

    =================================================================

    and this time i write log to check the issue , here it is :

    =================================================================

    Doing Activation 

    Name :SPAlertTemplateType.Announcements Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Announcements


    Name :SPAlertTemplateType.AssignedToNotification Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.AssignedToNotification


    Name :SPAlertTemplateType.Contacts Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Contacts


    Name :SPAlertTemplateType.DataConnectionLibrary Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.DataConnectionLibrary


    Name :SPAlertTemplateType.DiscussionBoard Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.DiscussionBoard


    Name :SPAlertTemplateType.DocumentLibrary Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.DocumentLibrary


    Name :SPAlertTemplateType.Events Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Events


    Name :SPAlertTemplateType.GenericList Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.GenericList


    Name :SPAlertTemplateType.Links Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Links


    Name :SPAlertTemplateType.PictureLibrary Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.PictureLibrary


    Name :SPAlertTemplateType.Survey Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Survey


    Name :SPAlertTemplateType.Tasks Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.Tasks


    Name :SPAlertTemplateType.WebPageLibrary Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.WebPageLibrary


    Name :SPAlertTemplateType.XMLForm Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :SPAlertTemplateType.XMLForm


    Name :WssDefaultTemplate Farm :SPFarm Name=SharePoint_Config_a56d9108-0549-489d-a660-80007230951d DisplayName :WssDefaultTemplate


    Error  :::::: 


    Failed to find template customalerttemplates.xmlin the template collection.

     =========================================================

    when i am trying to activate the featuer it is getting the error template not found :(, not sure why it is not finding templates, i see both of them are in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML

    and i have registered them using the stsadm -o templateupdate ...

    here is my Feature file

    ====================================================

      

    <?xml version="1.0" encoding="utf-8" ?>
    <Feature
      xmlns="http://schemas.microsoft.com/sharepoint/"
      Id="A9CEB138-B991-4013-A1F9-26C6BB646021"
        Title="DZT Alert Feature"
        Description="This is a feture doe custom email Template activation"
        Version="1.0.0.0"
        Scope="WebApplication"
        ReceiverAssembly="DZTFeature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=08cee0e2614eeba3"
        ReceiverClass="DZTFeature.DZTFeatureHandler"
        >
    </Feature>

    =========================================================things are look fine as directed in the links you gave me and few i find, please help me , i came long way i think , need little push from you guys :)

    Thanks and regardsTanmay Mandal

    Wednesday, October 31, 2012 3:54 PM
  • Hello guys, any update , can anyone help me on this, because i am not getting the point why my custom template is not working :( thanks and regards Tanmay Mandal
    Tuesday, November 06, 2012 3:59 PM
  • Here is the code i am using for mail sending , new is the log writing

    using System;
    using Microsoft.SharePoint;
    using System.Web;
    using Microsoft.SharePoint.Utilities;
    using System.Net.Mail;
    using System.Collections;
    using System.IO;

    namespace HandleEmailAlerts
    {
        class EmailNotifierHelper : IAlertNotifyHandler
        {
            #region IAlertNotifyHandler Members
            public bool OnNotification(SPAlertHandlerParams ahp)
            {
                string eventType = String.Empty;
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\Alertlog.log", true))
                {
                    stw.WriteLine("OnNotification fired\n");
                    try
                    {
                        SPSite site = new SPSite(ahp.siteUrl + ahp.webUrl);
                        SPWeb web = site.OpenWeb();
                        SPList list = web.Lists[ahp.a.ListID];
                        SPListItem item = list.GetItemById(ahp.eventData[0].itemId);


                        ahp.headers.Add("from", submittedBy.Email);
                        string FullPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl + "/" + list.Title + "/" + item.Name);
                        string ListPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl + "/" + list.Title);
                        string webPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "/" + ahp.webUrl);

                        string build = "";
                        SPUser spUser = null;
                        if (ahp.eventData[0].eventType == 1)
                        {
                            eventType = "Added";
                            spUser = (SPUser)item["Created By"];
                        }
                        else if (ahp.eventData[0].eventType == 2)
                        {
                            eventType = "Changed";
                            spUser = (SPUser)item["Modified by"];
                        }
                        else if (ahp.eventData[0].eventType == 3)
                        {
                            eventType = "Deleted";
                            spUser = (SPUser)item["Modified by"];
                        }

                        build = "<style type=\"text/css\">.style1 {font-size: small;       border: 1px solid #000000;" + "background-color: #DEE7FE;}.style2 {               border: 1px solid #000000;}</style></head>" + "<p><strong>" + item.Name.ToString() + "</strong> has been " + eventType + "</p>" + "<table style=\"width: 100%\" class=\"style2\"><tr><td style=\"width: 25%\" class=\"style1\">" + "<a href=" + webPath + "/_layouts/mysubs.aspx>Modify my Settings</a></td>" + "<td style=\"width: 25%\" class=\"style1\"> <a href=" + FullPath + ">View " + item.Name + "</a></td>" + "<td style=\"width: 25%\" class=\"style1\"><a href=" + ListPath + ">View " + list.Title + "</a></td>" + "        </tr></table>";
                        string subject = list.Title.ToString();
                        //SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), subject, build);
                        stw.WriteLine("Body address : \n\n");
                        stw.WriteLine(build);
                        stw.WriteLine("\n\n");
                        SendMail(subject, build, spUser.Email, ahp);
                        stw.WriteLine("To address : \n\n");
                        stw.WriteLine(ahp.headers["to"].ToString());
                        stw.WriteLine("\n\n");
                        return false;
                    }
                    catch (System.Exception ex)
                    {
                        stw.WriteLine("Error \n\n");
                        stw.WriteLine(ex.Message);
                        return false;
                    }
                }
            }
            /// <summary>
            /// Send mail from SMTP
            /// </summary>
            /// <param name="subject"></param>
            /// <param name="body"></param>
            /// <param name="from"></param>
            /// <param name="ahp"></param>
            private void SendMail(string subject, string body, string from, SPAlertHandlerParams ahp)
            {
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\Alertlog.log", true))
                {
                    try
                    {
                        stw.WriteLine("Email Sending \n");
                        MailMessage mMessage = new MailMessage();
                        mMessage.Subject = subject;
                        mMessage.Body = body;
                        
                        mMessage.From = new MailAddress(from);
                        mMessage.To.Add(ahp.headers["to"].ToString());
                       
                        mMessage.IsBodyHtml = true;
                        mMessage.Priority = MailPriority.High;
                        SmtpClient mSmtpClient = new SmtpClient();
                        System.Net.NetworkCredential credential = new System.Net.NetworkCredential("spemail@sample.com", "password");
                        mSmtpClient.Credentials = credential;
                        mSmtpClient.Host = "mail.haifire.com";
                        mSmtpClient.Port = 25;
                        mSmtpClient.Send(mMessage);
                        stw.WriteLine("Email Sent \n");
                    }
                    catch (Exception ex)
                    {
                        stw.WriteLine("Mail  Sending Error \n\n");
                        stw.WriteLine(ex.Message+"\n\n");
                    }
                }
            }
            #endregion
        }
    }

    Tuesday, November 06, 2012 4:16 PM
  • Hello,

    Have you seen this one : http://blogs.msdn.com/b/sharepointdeveloperdocs/archive/2007/12/07/customizing-alert-notifications-and-alert-templates-in-windows-sharepoint-services-3-0.aspx ?

    I see this that can maybe be the solution 

    Steps to Modify Alerts

    You can use any XML editing tool to edit the templates.

    1.       Create a working copy of AlertTemplates.xml.

    Note   Remember to always modify a copy of Alerttemplates.xml, not Alerttemplates.xml itself.

    1.       Edit the working copy that you just created.
    2.       Use the stsadm command to read the changed templates into the database.  STSADM -o updatealerttemplates -url <http://urlname> -filename <your working copy filename>.
    3.       Restart IIS.

    Note   It may be necessary to restart SharePoint Timer Services.

    Have you restarted all your services?


    Best regards, Christopher.
    Blog | Mail
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.
    Why mark as answer?

    Wednesday, November 07, 2012 8:14 AM
    Answerer
  • Hi Chris,

    Yes i have follow all the steps , not sure why it is not working :(

    even restart SharePoint Timer Services.

    thanks and regards

    Tanmay Mandal

    Wednesday, November 07, 2012 1:23 PM
  • Wednesday, November 07, 2012 3:07 PM
    Answerer
  • The simplest approach I can think of is to use ItemAdded event handler and then use System.Net.Mail to send email example http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

    Friday, November 09, 2012 12:20 AM
  • Hello Guys,

    Finally mail goes as required but new problem arise :(,  client demanding it effecting other site's alert, saying those alerts are stopped, even they register template on our site scope,

    In the template "SPAlertTemplateType.GenericList"

    <NotificationHandlerAssembly>HandleEmailAlerts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=53008e296bfdfad9</NotificationHandlerAssembly>
              <NotificationHandlerClassName>HandleEmailAlerts.EmailNotifierHelper</NotificationHandlerClassName>
              <NotificationHandlerProperties></NotificationHandlerProperties>

    in property section, and after client clamin it is effecting other alerts i have modified code too:

                                                         

      public bool OnNotification(SPAlertHandlerParams ahp)
            {
                string eventType = String.Empty;
                using (StreamWriter stw = new StreamWriter(@"D:\SPLog\Alertlog.log", true))
                {
                    stw.WriteLine("OnNotification fired\n");
                try
                {
                    SPSite site = new SPSite(ahp.siteUrl + ahp.webUrl);
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists[ahp.a.ListID];
                    SPListItem item = list.GetItemById(ahp.eventData[0].itemId);
                    string sEmail = String.Empty; //item.ListItems.List.Author.Email;
                    #region: Find Email addess in Loop of all User and List Created By
                    SPUserCollection spUsers = site.RootWeb.AllUsers;
                    string username = item["Modified by"].ToString();
                    int ID;
                    string name = "";
                    string[] arr = username.Split(new char[] { ';' });
                    ID = Convert.ToInt32(arr[0]);
                    name = arr[1].Replace("#", "");
                    foreach (SPUser u in spUsers)
                    {
                        if (u.Name == name && ID == u.ID)
                        {
                            sEmail = u.Email;
                            break;
                        }
                    }
                    #endregion


                    if (item.ListItems.List.Title.ToLower() == "conflict check form")
                    {

                        stw.WriteLine("Body  : \n\n");
                        stw.WriteLine(ahp.body);
                        stw.WriteLine("\n\n");
                        stw.WriteLine("From  : \n\n");
                        stw.WriteLine(sEmail);
                        stw.WriteLine("\n\n");
                        stw.WriteLine("To  : \n\n");
                        stw.WriteLine(ahp.headers["to"].ToString());
                        stw.WriteLine("\n\n");
                        stw.WriteLine("Mail Sending Start");
                        try
                        {
                            if (sEmail.Trim().Length > 0)
                            {
                                SendMail(ahp.headers["Subject"], ahp.body, sEmail, ahp.headers["to"].ToString());
                                stw.WriteLine("Mail Sent from SMTP");
                            }
                            else
                            {
                                SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), ahp.headers["Subject"], ahp.body);
                                stw.WriteLine("Mail send from Default address as Email address of the user not found");
                            }

                        }
                        catch (Exception ex)
                        {
                            //if failed then pass default email from SPUtility
                            SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), ahp.headers["Subject"], ahp.body);
                            stw.WriteLine("Mail Sent from SP mail configuration");
                             throw new Exception(ex.Message);
                        }
                    }
                    else
                    {
                        //Second level protection from code if template added globally , then mail will go from here if list name is "Conflict Check Form" only then custom email will apply
                        SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), ahp.headers["Subject"], ahp.body);
                    }

                    return false;
                }
                catch (System.Exception ex)
                {
                    stw.WriteLine("Error \n\n");
                    stw.WriteLine(ex.Message);

                    return false;
                }
                }
            }

    but they are saying it is stopped working for other sites , though in my code there is option to pass alert through normal system if it is not from my list.

     if (item.ListItems.List.Title.ToLower() == "conflict check form")
                    {

    // do custom code

    }

     else
                    {
                        //Second level protection from code if template added globally , then mail will go from here if list name is "Conflict Check Form" only then custom email will apply
                        SPUtility.SendEmail(web, true, false, ahp.headers["to"].ToString(), ahp.headers["Subject"], ahp.body);
                    }

    do not know why?

    what do you suggest

    1) Did they need to check other email alerts for long time , because timer may be do it after few more min.

    2) or i should create new template and from feature i should update list alert template? and i think this process a bit complicated :(

    guys please help me.

    thanks and regards

    Tanmay Mandal

    Tuesday, November 13, 2012 4:30 AM
  • What do you mean by 

    "Finally mail goes as required but new problem arise :(,  client demanding it effecting other site's alert, saying those alerts are stopped, even they register template on our site scope,"

    Are you talking about out of the box alert or about your custom alert?


    Best regards, Christopher.
    Blog | Mail
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.
    Why mark as answer?

    Tuesday, November 13, 2012 8:33 AM
    Answerer
  • Hello Chris,

    Alert is integrated with the List , as on my list there are other site in site collection and also have alert on item add , 

    When my code and template is deployed in server my custom alert is working fine [as required], but alert of other sites not working as client said , they are saying they add item in there other site but did not get alert , which was working before deploy new update and even after roll back it's working .

    So good thing is 

    1) my custom alert working fine 

    bad thing

    1) It is effecting other sites in site collection , and there alert system seems not working .

    hope you got my problem , and i have mailed you everything , what should I do, 

    should i create another template [not file] in customalert.xml, with another name and through feature update list's alert template ?

    and if it is not working what might be the cause ? any idea?

    thanks and regards

    Tanmay Mandal

    Wednesday, November 14, 2012 6:09 AM