Creating message body by parsing document from Document Library and sending mail in SharePoint 2007

No.of Views1010
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  06 Apr 2010 09:04:21
Tag : SharePoint , Development and Programming
How to parse a document from Document Library and replace with dynamic values at run time,How to send mail in SharePoint using SPUtility class,Introduction of a real time problem to use above said features of SharePoint.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

This article will give an idea of,
1.    How to parse a document from Document Library and replace with dynamic values at run time.
2.    How to send mail in SharePoint using SPUtility class.
3.    Introduction of a real time problem to use above said features of SharePoint.
 

Background

There was a requirement in one of my project. I will divide requirement as follows
1.    There are documents in Document Library.
2.    Content of documents will be sending as body of Email.
3.    Document will be containing static data as well as dynamic data.
4.    Value for dynamic data will be replaced at the run time.
 

So, requirement could be summarized as; we need to fetch a document from document library and parse that. While parsing, we will replace dynamic variables with real value and then we will be sending the mail. Content of the document will be parsed as string and will be sent as body of the mail.
Let us say, we are having a document   named Notification.txt in SharePoint Document library. Content of document is as follows
 

Notification.txt

Image Loading

Note: Dynamic variables are enclosed in square braces.

1.    We need to read this document from SharePoint Document library using object model.
2.    Replace dynamic variables enclosed with square braces with values at run time.
3.    Parse content of document and return a string. This string will be used as body of the mail.
Finally after creating body from document of document library, we will send mail using SPUtility.


Creating Body from Document of SharePoint Document Library
 

Step 1: Create Hash Table

Hash table will contain values for all the dynamic variables.

public Hashtable CreateHashTableForMessageBody(string name, string managerName,string date, string projectName, string linkToNavigate)
 {
Hashtable hashTableForMessageBody = new Hashtable();          
link = String.Format("<a href = {0} >click here.</a>", linkToNavigate);
hashTableForMessageBody.Add("Name", name);
hashTableForMessageBody.Add("ManagerName", managerName);
hashTableForMessageBody.Add("Date", date);
hashTableForMessageBody.Add("ProjectName", projectName);
hashTableForMessageBody.Add("UriToNavigate",link);
return hashTableForMessageBody;
}

1.     We are passing all the required values for dynamic variables as input parameter to function.
2.    We are creating a Hash table.
3.    Function is returning a hash table.
4.    Make sure name of the key is exactly the same as of name of the dynamic variables. Dynamic variables are enclosed in square braces.  Cases of the Dynamic variables and key of hash table must be same.  For example key “Name” in Hash table will be parsed and replaced for [Name] dynamic variable in document.
 

Step 2: Parsing content of document to return a string as message body. 

Public static string GetEmailBody(String spSite, Hashtable emailAttribute, string templateName)
        {
            
            string templateStr = "";
            string bottomMessage = "";
            try
            {
                using (SPSite site = new SPSite(spSite))
                {
                    using (SPWeb uspWeb = site.OpenWeb())
                    {
                        this.emailAttributes = emailAttributes;
               SPList emailTemplates = uspWeb.Lists["NotificationTemplate"];
               SPQuery qry = new SPQuery();
               qry.Query = string.Format("<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>{0}</Value></Eq></Where>", templateName);
     SPListItemCollection templateCollection = emailTemplates.GetItems(qry);
     if (templateCollection.Count > 0)
      {
        SPListItem template = templateCollection[0];
        byte[] templateByte = template.File.OpenBinary();
        System.Text.Encoding enc = System.Text.Encoding.ASCII;
        templateStr = enc.GetString(templateByte);
        foreach (object obj in emailAttribute.Keys)
         {
          if (emailAttribute[obj] != null)
             {
          
        templateStr = templateStr.Replace("[" + obj.ToString() + "]",   emailAttribute[obj].ToString());
            
           }
       }
  bottomMessage = "*** This is system-generated email.  Do not reply. *** ";
  templateStr = templateStr +"\n" + bottomMessage;

}
                        
            return templateStr;
        }

1.    Function takes three input parameters.  First parameter is URL as string to create instance of SPSIte. Second parameter is Hash table. Third parameter is name of the template to be parsed.
2.    NotificationTemplate is name of the Document Library in SharePoint site.
3.    We are iterating through the Document library using CAML query and searching for the template name (.txt file uploaded)
4.    We are iterating through all the keys in hash table and replacing the keys with values while getting matched with dynamic variable in document of document library.
5.    We are returning string message as body of the mail.
 

Sending mail using SPUtility

So far, we have created the body of the mail; we are going to send.  In this section we will see how we can send Email using SPUtility class on Windows.SharePoint.Services.dll
1.    Creating hashtable to create message body.
2.    Passing hashtable in function creating messagebody.
3.    Creating a dictionary to set To, From, Subject and Body of the mail.
4.    SendMail static function of SPUtility class is used to send mail.


Function to send Email using SPUtility
 

String name = “Dhananjay Kumar”
            Striing subject = String.Empty;
            String managername =”Anoj P”
            String linktonavigate = “Default.apsx”;
            String date = String.Empty;
            String projectname = “My Project”;
            String messageBody = String.Empty;
            Hashtable hashTableForMessageBody = null;           
hashTableForMessageBody = CreateHashTableForMessageBody(name, managername, date, projectname,linktonavigate);
messageBody = GetEmailBody(spsite, hashTableForMessageBody, Notification.txt);

    #region sending Mail
            subject = “This is Test Mail”
            try
            {
                StringDictionary headers = new StringDictionary();
                headers.Add("subject", subject);
                headers.Add("from", GetFromAddress(spsite));
                headers.Add("to",”abc@abc.com”);
                SPUtility.SendEmail(web, headers, messageBody);
            }
            catch (Exception ex)
            {
                web.Dispose();
                site.Dispose();
                ErrorLogger.LogError("Creating message Body - sending mail", ex);
            }
            #endregion

 

That's all,

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page- http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top