locked
To send an email on a date(specified in list) using Timer job. RRS feed

  • Question

  • Hi,

       I need to send an email on a particular date specified in the list.

    I have 4 date columns in list, If date occurs today, user should get triggered an email using Timer Job.

    Please help me in this with an appropriate solution.

    Thanks in Advance.


    Badri

    Monday, August 19, 2013 7:01 AM

Answers

  • public override void Execute(Guid contentDbId) { SPSite site = new SPSite(WebUrl);

    SPWeb web = site.OpenWeb();

    SPList yourList = web.Lists.TryGetList("YourListTitle");

    SPListItem item = yourList.GetItems("Your CAML Query")[0];

    if(Convert.ToDateTime(item["columnName"]).Equals(DateTime.Today))

    { string from = string.Empty; string smtpAddress = string.Empty; string to = "Email id of receiver"; string subject = "Email Notification"; string body = " Records"; SPSecurity.RunWithElevatedPrivileges(delegate() { // get a reference to the current site collection's content database SPWebApplication webApplication = this.Parent as SPWebApplication; SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId]; // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database SPWeb rootWeb = contentDb.Sites[0].RootWeb; SPList listjob = rootWeb.Lists.TryGetList("ListName"); // Get sender address from web application settings from = rootWeb.Site.WebApplication.OutboundMailSenderAddress; // Get SMTP address from web application settings smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address; // Send an email if the news is approved bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null); if (listjob != null && emailSent) { SPListItem newListItem = listjob.Items.Add(); newListItem["Title"] = string.Concat("Email Notification Sent at : ", DateTime.Now.ToString()); newListItem.Update(); } });

    } } public bool SendMail(string smtpAddress, string subject, string body, bool isBodyHtml, string from, string to, string cc, string bcc) { bool mailSent = false; SmtpClient smtpClient = null; try { // Assign SMTP address smtpClient = new SmtpClient(); smtpClient.Host = smtpAddress; //Create an email message MailMessage mailMessage = new MailMessage(from, to, subject, body); if (!String.IsNullOrEmpty(cc)) { MailAddress CCAddress = new MailAddress(cc); mailMessage.CC.Add(CCAddress); } if (!String.IsNullOrEmpty(bcc)) { MailAddress BCCAddress = new MailAddress(bcc); mailMessage.Bcc.Add(BCCAddress); } mailMessage.IsBodyHtml = isBodyHtml; // Send the email smtpClient.Send(mailMessage); mailSent = true; } catch (Exception) { mailSent = false; } return mailSent; }


    #RoHsTr

    • Marked as answer by Lindali Wednesday, August 28, 2013 12:46 PM
    Monday, August 19, 2013 10:37 AM

All replies

  • Create a class inheriting from SPJobDefinition

    And use following code to get email from timer job

     public override void Execute(Guid contentDbId)
            {
              
                string from = string.Empty;
                string smtpAddress = string.Empty;
                string to = "Email id of receiver";
                string subject = "Email Notification";
                string body = " Records";         
                 
    
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // get a reference to the current site collection's content database 
                    SPWebApplication webApplication = this.Parent as SPWebApplication;
                    SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
    
                    // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database 
                    SPWeb rootWeb = contentDb.Sites[0].RootWeb;
    
                     
                    SPList listjob = rootWeb.Lists.TryGetList("ListName");
    
                    // Get sender address from web application settings 
                    from = rootWeb.Site.WebApplication.OutboundMailSenderAddress;
    
                    // Get SMTP address from web application settings 
                    smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
    
                    // Send an email if the news is approved 
                    bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null);               
    
                    if (listjob != null && emailSent)
                    {
                        SPListItem newListItem = listjob.Items.Add();
                        newListItem["Title"] = string.Concat("Email Notification Sent at : ", DateTime.Now.ToString());
                        newListItem.Update();
                    }
                });
            }
    
            
            public bool SendMail(string smtpAddress, string subject, string body, bool isBodyHtml, string from, string to, string cc, string bcc)
            {
                bool mailSent = false;
                SmtpClient smtpClient = null;
    
                try
                {
                    // Assign SMTP address 
                    smtpClient = new SmtpClient();
                    smtpClient.Host = smtpAddress;
    
                    //Create an email message 
                    MailMessage mailMessage = new MailMessage(from, to, subject, body);
                    if (!String.IsNullOrEmpty(cc))
                    {
                        MailAddress CCAddress = new MailAddress(cc);
                        mailMessage.CC.Add(CCAddress);
                    }
                    if (!String.IsNullOrEmpty(bcc))
                    {
                        MailAddress BCCAddress = new MailAddress(bcc);
                        mailMessage.Bcc.Add(BCCAddress);
                    }
                   
                    mailMessage.IsBodyHtml = isBodyHtml;
    
                    // Send the email 
                    smtpClient.Send(mailMessage);
                    mailSent = true;
                }
                catch (Exception)
                {
                    mailSent = false;
                }
    
                return mailSent;
            }
    Here in this code u can get weekly mail, similarly u can set it for daily , monthly

    Let me know if u have any query.

    Thanks

    -Rahul

    Monday, August 19, 2013 8:23 AM
  • If you want to do this through only timer job then above solution is good

    But i will siggest you to use workflow for the same issue.

    Monday, August 19, 2013 10:16 AM
  • public override void Execute(Guid contentDbId) { SPSite site = new SPSite(WebUrl);

    SPWeb web = site.OpenWeb();

    SPList yourList = web.Lists.TryGetList("YourListTitle");

    SPListItem item = yourList.GetItems("Your CAML Query")[0];

    if(Convert.ToDateTime(item["columnName"]).Equals(DateTime.Today))

    { string from = string.Empty; string smtpAddress = string.Empty; string to = "Email id of receiver"; string subject = "Email Notification"; string body = " Records"; SPSecurity.RunWithElevatedPrivileges(delegate() { // get a reference to the current site collection's content database SPWebApplication webApplication = this.Parent as SPWebApplication; SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId]; // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database SPWeb rootWeb = contentDb.Sites[0].RootWeb; SPList listjob = rootWeb.Lists.TryGetList("ListName"); // Get sender address from web application settings from = rootWeb.Site.WebApplication.OutboundMailSenderAddress; // Get SMTP address from web application settings smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address; // Send an email if the news is approved bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null); if (listjob != null && emailSent) { SPListItem newListItem = listjob.Items.Add(); newListItem["Title"] = string.Concat("Email Notification Sent at : ", DateTime.Now.ToString()); newListItem.Update(); } });

    } } public bool SendMail(string smtpAddress, string subject, string body, bool isBodyHtml, string from, string to, string cc, string bcc) { bool mailSent = false; SmtpClient smtpClient = null; try { // Assign SMTP address smtpClient = new SmtpClient(); smtpClient.Host = smtpAddress; //Create an email message MailMessage mailMessage = new MailMessage(from, to, subject, body); if (!String.IsNullOrEmpty(cc)) { MailAddress CCAddress = new MailAddress(cc); mailMessage.CC.Add(CCAddress); } if (!String.IsNullOrEmpty(bcc)) { MailAddress BCCAddress = new MailAddress(bcc); mailMessage.Bcc.Add(BCCAddress); } mailMessage.IsBodyHtml = isBodyHtml; // Send the email smtpClient.Send(mailMessage); mailSent = true; } catch (Exception) { mailSent = false; } return mailSent; }


    #RoHsTr

    • Marked as answer by Lindali Wednesday, August 28, 2013 12:46 PM
    Monday, August 19, 2013 10:37 AM
  • Hi Rahul,

      Thanks for the code. This helps me a lot.

    I have some queries.

    Could please let me know the below mentioned details:

    1). What should i mention in the records    String body = "Records";

    2).what should i need to specify in the line.

     SPWeb rootWeb = contentDb.Sites[0].RootWeb;

    3).What should i specify in 

    from = rootWeb.Site.WebApplication.OutboundMailSenderAddress;

     smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;

    4).where should i need to specify list columns to fetch particular's date to send an email.

    5).where should i change it to daily, to check daily & send email if the date exists on the date.

    Thanks in advance.



    Badri

    Tuesday, August 20, 2013 7:42 AM
  • Hi Rahul,

            Finally, I need the list items also get populated in the email of the particular date.

    Is this possible to fetch only few columns details within the email.


    Badri

    Tuesday, August 20, 2013 10:55 AM
  • Badri,

    Its quit simple ,

    Just query(here according to u its date) against list items and save them in some variable, then pass that value as a parameter(Body).

    Thanks

    -Rahul

    Tuesday, August 20, 2013 11:01 AM
  • Hi Rahul,

        Could you please help me out with an example in the code:

    I had created 4 designer workflows for 4 columns in my list.

    My idea is to add this 4 workflows GUID's in the code and deploy the timer job

    Can you please highlight the spaces where i need to place the input's required for the deployment of timer job.

    Like: GUID,

    Site url,

    list name,

    time schedule need to specify when timer job should run.

    Overall inputs need to specify to deploy the timer job.

    Thanks in Advance.


    Badri

    Wednesday, August 21, 2013 1:31 PM