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

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

4 responses to “Creating message body by parsing document from Document Library and sending mail in SharePoint 2007”

  1. Прочитав статью в полном развороте здесь
    вывод сам напрашивается, глядя на их сервис и сам товар ими продаваемый,
    впечатление складывается что бош занимается разводом, как только до гарантии
    доходит “мол товар не наш а китайская подделка”, у этого мужика оригинальный
    талон это же видно да и переписку такую бы с таким бредом они бы не устроили
    если б это была лажа, по тексту просто прессинг был, думаю сам бош не тот что
    был 10 лет назад, сегодня это гавноделы такие же как китайский ширпотреб.
    Мое мнение, да BOSCH гавно или фуфло если хотите, я такой товар, это я для себя
    сделал вывод, я покупать не буду да и друзьям не посоветую.

  2. Benkir.net- на нашем сайте вы найдете как лучшие футболки, прикольные на любой выбор.
    Мы принимаем любые намерение платежей.
    http://benkir.net/ – купить футболки Украина

  3. Did you know Morgan International offering CIM Certificate? It’s an ideal marketing designation prep course!

  4. […] Creating message body by parsing document from Document Library and sending mail in SharePoint 2007 […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com