none
Iterate through sharepoint document library and send e-mail through custom timer job RRS feed

  • Question

  • I am not a very good programmer and I managed to collect some parts of the puzzle but don't know how to put them together.

    I have implemented a custom timer job to send an e-mail with a simple text as the body.

    My next step is to loop through items in a Sharepoint document library, collect all the url's and send it 1 e-mail. I followed exactly what is told here: http://blogs.msdn.com/b/guruketepalli/archive/2012/01/23/sharepoint-2010-custom-timer-job-send-an-email.aspx

    This is the custom timer job.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Administration;
    using Microsoft.SharePoint;
    using System.Net.Mail;
    namespace NotificationCustomTimerJob
    {
        public class NotificationTimerJob : Microsoft.SharePoint.Administration.SPJobDefinition
        {
            /// <summary>  
            /// Default Consructor  
            /// </summary>  
            public NotificationTimerJob()
                : base()
            {
            }
            /// <summary>  
            /// Parameterized Constructor  
            /// </summary>  
            /// <param name="jobName">Name of Job to display in central admin</param>  
            /// <param name="service">SharePoint Service </param>  
            /// <param name="server">Name of the server</param>  
            /// <param name="targetType">job type is for content db or job</param>  
            public NotificationTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
                : base(jobName, service, server, targetType)
            {
            }
            /// <summary>  
            /// Parameterized Constructor  
            /// </summary>  
            /// <param name="jobName"></param>  
            /// <param name="webApplication"></param>  
            public NotificationTimerJob(string jobName, SPWebApplication webApplication)
                : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
            {
                this.Title = "Email Notification Job";
            }
            /// <summary>  
            /// Execute method called when the timer job starts executing. It runs on "DB News Announcements" list which checks for all  
            /// approved annoucements and sends out an email to all users for all approved news.  
            /// </summary>  
            /// <param name="contentDbId"></param>  
            public override void Execute(Guid contentDbId)
            {
                string from = string.Empty;
                string smtpAddress = string.Empty;
                string to = "someone@example.com";
                string subject = "Email Notification";
                string body = "<h1> Email Sending from Email Notification Job </h1>";
                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;
                    // Get the DB News Announcements List  
                    SPList listjob = rootWeb.Lists.TryGetList("Tasks");
                    // 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();
                    }
                });
            }
            /// <summary>  
            /// Send an email to indented users  
            /// </summary>  
            /// <param name="smtpAddress">SMTP address to sending email</param>  
            /// <param name="subject">subject of email</param> 
            /// <param name="body">body of email</param>  
            /// <param name="isBodyHtml">whether body is html or text</param>  
            /// <param name="from">from address</param>  
            /// <param name="to">to users(multiple email address can be seperated by comma(,) )</param>  
            /// <param name="cc">cc users</param>  
            /// <param name="bcc">bcc users</param>  
            /// <returns>Status whether email successfully sent or not</returns>  
            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;
            }
        }
    }

    THis is the event receiver for the custom timer job:

    using System;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Security;
    using System.Linq;
    namespace NotificationCustomTimerJob.Features.NotificationTimerJobFeature
    {
        /// <summary>
        /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
        /// </summary>
        /// <remarks>
        /// The GUID attached to this class may be used during packaging and should not be modified.
        /// </remarks>
        [Guid("9a026564-9131-42b8-ba13-29b9afab4817")]
        public class NotificationTimerJobFeatureEventReceiver : SPFeatureReceiver
        {
            // Name of the Timer Job, but not the Title which is displayed in central admin  
            private const string List_JOB_NAME = "NotificationTimerJob";   
            // Uncomment the method below to handle the event raised after a feature has been activated.   
            public override void FeatureActivated(SPFeatureReceiverProperties properties)  
            {  
                SPSecurity.RunWithElevatedPrivileges(delegate()  
                {  
                    SPSite site = properties.Feature.Parent as SPSite;   
                    // make sure the job isn't already registered  
                    site.WebApplication.JobDefinitions.Where(t => t.Name.Equals(List_JOB_NAME)).ToList().ForEach(j => j.Delete());  
                    // install the job  
                    NotificationTimerJob listLoggerJob = new NotificationTimerJob(List_JOB_NAME, site.WebApplication);  
                    SPMinuteSchedule schedule = new SPMinuteSchedule();  
                    schedule.BeginSecond = 0;  
                    schedule.EndSecond = 59;  
                    schedule.Interval = 5;  
                    listLoggerJob.Schedule = schedule;  
                    listLoggerJob.Update();  
                });  
            }    
            // Uncomment the method below to handle the event raised before a feature is deactivated.   
            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)  
            {  
                SPSecurity.RunWithElevatedPrivileges(delegate()  
                {  
                    SPSite site = properties.Feature.Parent as SPSite;   
                    // delete the job  
                    site.WebApplication.JobDefinitions.Where(t => t.Name.Equals(List_JOB_NAME)).ToList().ForEach(j => j.Delete());  
                });  
            }    
            // Uncomment the method below to handle the event raised after a feature has been installed.   
            //public override void FeatureInstalled(SPFeatureReceiverProperties properties)  
            //{  
            //}    
            // Uncomment the method below to handle the event raised before a feature is uninstalled.   
            //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)  
            //{  
            //}  
            // Uncomment the method below to handle the event raised when a feature is upgrading.   
            //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)  
            //{  
            //} 
        }
    }

    Also, i found this piece of code which iterates through items in a list. (Don't know if this would work for a library?)

    foreach(SPListItem item in spList.Items){
      SPFieldUrlValue data = item["Url"] as SPFieldUrlValue;
    }

    I am finding a hard time putting everything together. Can anybody guide me through this? Thanks....

    • Edited by mikello Friday, May 17, 2013 2:19 PM Added code
    Friday, May 17, 2013 2:08 PM

Answers

  • You would add it to the execute method for the timer job. At this stage 'body' just gets assigned a static string so you would just need to query the applicable list and create your body string.
    • Proposed as answer by Emir Liu Monday, May 20, 2013 6:53 AM
    • Marked as answer by Emir Liu Thursday, May 23, 2013 6:57 AM
    Friday, May 17, 2013 2:44 PM

All replies

  • Yep, that code would work if you get your SPList.

    Rather than iterating through all the items, if you are only getting subset of the items it is probably best to use SPQuery to query the list first and then iterate over this. See the example in the article below.

    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spquery.aspx

    Once you get your items it should just be a matter of building up the body of the email.

    If you combine this with the article you pasted this should be pretty much it.

    Friday, May 17, 2013 2:23 PM
  • Here is where I am getting lost, I am unable to combine the codes. Pardon my lack of knowledge on coding...I don't know where to insert that code in my timer job :(
    Friday, May 17, 2013 2:37 PM
  • You would add it to the execute method for the timer job. At this stage 'body' just gets assigned a static string so you would just need to query the applicable list and create your body string.
    • Proposed as answer by Emir Liu Monday, May 20, 2013 6:53 AM
    • Marked as answer by Emir Liu Thursday, May 23, 2013 6:57 AM
    Friday, May 17, 2013 2:44 PM