Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Convert Outlook Table Content into Datatable using C# EWS and HtmlAgilitypack

0.00/5 (No votes)
1 Nov 2017 1  
Convert table from outlook email body into datatable or list<T> using .NET C# EWS Managed API and HtmlAgilitypack

Introduction

In this post, we will look at the parsing of table containing inside outlook email body using .NET C#, EWS Managed API and HtmlAgilitypack.EWS (Web service in exchange) allow us to access Microsoft Exchange such as EMAIL, Contacts, Calendar. For more details about EWS, visit this link.

Background

This tips is for developers, tech leads and tech community.

Open Visual Studio 2017 Community Edition

Open Visual Studio 2017, Go To New -> Project. Select Visual C# -> Windows Classic desktop from the left hand navigation and select project type as ConsoleApp(.NET Framework). Enter the project name as ParseOutlookContents.

Add Project.

Installing HtmlAgilityPack and Microsoft.Exchange.WebServices

We will then add the HtmlagilityPack and Microsoft.Exchange.WebServices libraries in our project using the NuGet Package Manager which makes it very easy to install the libraries in our project.

Right click on project > select Manage Nuget Packages and search for HtlmagilityPack and Microsoft.Exchange.WebServices in browse tab. Install both the libraries in the project.

Add Libraries.

After adding libraries, expand project references folder and see whether the libraries are added in reference folder.

.dll references

Open program.cs and add the following namespace on the top.

// Using Microsoft.Exchange.WebServices.Data;
// Using Htmlagilitypack;

Add the below method in program.cs:

Static Datatable Renderdatatable()
      {
          Datatable Dt = New Datatable("mytable");
          Exchangeservice Service = New ExchangeService(ExchangeVersion.Exchange2007_SP1);
          service.Credentials = New WebCredentials("saurav.J@domain.com", "Xyz@2017");

          service.TraceEnabled = True;
          service.TraceFlags = TraceFlags.All;
          String Ews_serviceurl = "https://outlook.office365.com/EWS/Exchange.asmx";
          service.Url = New Uri(ews_serviceurl);
          Folder Rootfolder = Folder.Bind(service, WellKnownFolderName.Inbox);
          rootfolder.Load();
          Folder Foundfolder = rootfolder.FindFolders
               (new FolderView(100)).FirstOrDefault(x => x.DisplayName == "Saurav");
          if (Foundfolder != null)
          {
              Finditemsresults<item> Findmsg1 = service.FindItems(foundFolder.Id, New Itemview(10));
              Foreach (Item Item1 in findmsg1.Items)
              {
                  if (Item1 Is Emailmessage)
                  {
                      item1.Load();
                      Stringbuilder Builder = New Stringbuilder();
                      builder.Append(item1.Body.Text.ToString());

                      Htmldocument HTML = New Htmldocument();
                      html.LoadHtml(builder.ToString());

                      dt.Columns.Add("#RR", Typeof(string));
                      dt.Columns.Add("Nota Fiscal", Typeof(string));
                      dt.Columns.Add("Dt Emissão", Typeof(string));
                      dt.Columns.Add("Fornecedor", Typeof(string));
                      Var Query = From Table in html.DocumentNode.SelectNodes("//table")
                                  Where table.Descendants("tr").Count() > 1 //Make Sure
                                                          //there are Rows Other Than Header Row
                                  From Row in table.SelectNodes((".//tr[position()>1]")) //Skip the
                                                                                         //Header Row
                                  Select New
                                  {
                                      Table = table.Id,
                                      Row = row.InnerText
                                  };

                      Foreach (Var R in query.Select(x => x.Row))
                      {
                          Datarow Dr = dt.NewRow();
                          String Str = Regex.Replace(r.ToString(), @"\R\n\r\n\r\n", ",").Trim();

                          String[] Str1 = str.Split(',');
                          if (str1.Length > 0)
                          {
                              Int I = 0;
                              Foreach (String Valitem in str1)
                              {
                                  Dr[i] = Valitem;
                                  i++;
                              }
                              dt.Rows.Add(dr);
                          }
                      }
                  }
              }
          }
          Return Dt;
      }

This code is reading HTML table containing inside email body from inbox custom folder "Saurav" and rendering it into datatable. However, we can read content from Outbox, Calendar, Draft respectively. But in the code, we need to make changes accordingly.

Folder rootfolder = Folder.Bind(service, WellKnownFolderName.Outbox);

Select the options from WellKnownFolderName enums as per your requirement.

Conclusion

The purpose of this article is to demonstrate how easily you can render HTML table from Outlook email body into datatable using .NET C#. In the next article, we will discuss about the implementation of similar requirement in .NET Core.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here