Monday, March 1, 2010

Send Reminder mail based on Date field in SharePoint List

Below is the C# console application program to send reminder mail to user, seven days prior to due date.
It is used check WSS 3.0 list item and send mail.

Add Microsoft.SharePoint.dll in your project.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Net.Mail;

namespace MailSending
{
    class Program
    {
        static string strMailFrom = "MailId";
        static string[] strMailTo = new string[] { "MailId", "MailId" };

        static void Main(string[] args)
        {
            SPSite oSite = new SPSite("SiteURLHere");
            SPWeb oWeb = oSite.OpenWeb();
            SPList oList = oWeb.Lists["ListNameHere"];

            for (int i = 0; i < oList.Items.Count; i++)
            {
                SPListItem oListItem = oList.Items[i];
                DateTime dtDate = Convert.ToDateTime(oListItem["Due Date"]);
                DateTime dtToday = DateTime.Today;
                TimeSpan TS = dtDate.Subtract(dtToday);
                if (TS.Days == 7)
                    SendMail(oList.Items[i].ID.ToString(), Convert.ToDateTime(oListItem["Due Date"]).ToShortDateString());
            }           
        }

        static void SendMail(string strListItemID, string strDueDate)
        {
            MailMessage message = new MailMessage();
            message.Subject = "This is Subject";
            message.From = new MailAddress(strMailFrom);

            for (int j = 0; j < strMailTo.Length; j++)
                message.To.Add(strMailTo[j]);

            string strMsgBody = "Please note that Due Date is " + strDueDate + ". Please check the below list for more information.
";
            strMsgBody += "" + strDueDate + ";

            message.Body = strMsgBody;
            message.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient("SMTP_Address_Here");
            smtp.Send(message);
        }
    }
}

After compiling we can take the exe file of this application and add in windows Task Scheduler. So that it will send mail to user.

No comments:

Post a Comment