.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Home >> Articles >> SharePoint >> Post New Resource Bookmark and Share

 Subscribe to Articles

Parse document from Document Library and send mail in SharePoint

Posted By :Dhananjay Kumar      Posted Date :08/02/2010   Points :25   Category: SharePoint    URL: http://www.dotnetspark.com

Parse document from Document Library and send mail in SharePoint. In this article we will see how to Create message body by parsing document from Document Library and send mail in SharePoint
    


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

Hi [Name],  

This is   Notification Mail From SharePoint server. You are supposing to Report to [ManagerName] on [Date] for the [ProjectName].

 

[UriToNavigate] to Navigate.

 

Thanks with Regards.

 

***Do not reply to this mail***

 

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


Featured Articles


Best Practices No 5: - Detecting .NET application memory leaks
Memory leaks in .NET application have always being programmer's nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime. ... Read More
.NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
One of the important factors for performance degradation in .NET code is memory consumption. Many developers just concentrate on execution time to determine performance bottle necks in a .NET application. Only measuring execution time does not clearly give idea of where the performance issue resides. Ok, said and done one of the biggest task is to understand which function, assembly or class has consumed how much memory. In this tutorial we will see how we can find which functions consume how much memory. This article discusses the best practices involved using CLR profiler for studying memory allocation.... Read More
How to improve your LINQ query performance by 5 X times ?
LINQ has been criticized by many early adopters for its performance issues. Well if you are just going to drag and drop using DBML code generator I am sure you will land up in to mess. Try doing this make a simple LINQ to SQL project using DBML and see your SQL profiler, I am sure you will never like to touch DBML code generator again. ... Read More
Responses

No response found. Be the first to respond this post

Post Comment
You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend