Click here to Skip to main content
15,883,705 members
Articles / Web Development / XHTML
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
1 Nov 2017CPOL1 min read 13.3K   2  
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.

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

Add the below method in program.cs:

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I am saurav J working as senior technical consultant, Bangalore India.
PMI Agile Certified Practitioner-(ACP).

Comments and Discussions

 
-- There are no messages in this forum --