Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Sharepoint » Creating message body by parsing document from Document Library and sending mail in SharePoint 2007

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

This article will give an idea of, 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 and Introduction of a real time problem to use above said features of SharePoint.

Author Rank:
Total page views :  1061
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


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);


    #regiononon sending Mail
            subject = "This is Test Mail"
            try
            {
                StringDictionary headers = new StringDictionary();
                headers.Add("subject", subject);
                headers.Add("from", GetFromAddress(spsite));
                headers.Add("to"mailto:to%22,);
                SPUtility.SendEmail(web, headers, messageBody);
            }
            catch (Exception ex)
            {
                web.Dispose();
                site.Dispose();
                ErrorLogger.LogError("Creating message Body - sending mail", ex);
            }
            #endregion


Login to add your contents and source code to this article
 About the author
 
Dhananjay Kumar
I am Dhananjay Kumar. I passed computer science  & engineering from AEC Agra in year 2007. I born and brought up in Jamshedpur , Jharkhand.I am MCTS on WCF, MOSS Development , .Net Framework 2.0 Web Application so far. I read and write on WCF, SilverLight , SharePoint , ASP.Net MVC, ASP.Net 3.5 Extensions , .Net 4.0 , C# 3.0 , C# 4.0 etc etc. Currently , I am working for UST Global as Software Engineer and active member of Microsoft COE team .
 
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.