Reading Email and Attachment From Microsoft Exchange Server

Introduction 

This article shows how to create an application that reads email and its attachment(s) from Microsoft Exchange Server. You can read emails from any folder like Inbox, Outbox, and so on. In this tutorial I will be reading emails from the Inbox folder. You can also set up a filter on what type of emails you what to read. I will be filtering based on Date. 
 
Prerequisites
  1. Microsoft Exchange WebServices (we can install it from NuGet Package Manager).

  2. Valid Microsoft Exchange Server User Account.

  3. Visual Studio 2010+.
 I will be creating a Windows Form application in this tutorial.
 
Step 1

Create a New Project > Windows Forms Application. Open Visual Studio then create a New Project, then go to Templates and select Visual C#, then Windows and select Windows Forms Application.

Type in a decent project name. I named the project "ReadMailFromExchangeServer".
 
Step 2

Install Microsoft Exchange WebServices. Click on Tools, then NuGet Package Manager > Package Manager Console.

Type: Install-Package Microsoft.Exchange.WebServices. In a while the  Microsoft.Exchange.WebServices will be installed in your application.

Step 3

Design the user interface. Add the following controls:
Control Name Text
Button btnRead Read Today's Email
ListView lstMsg  
Button btnLoad Load Attachment
Label lblMsg Ready
Label label1 Today's Mail
Label lblAttach No Attachment downloaded

mail

Step 4

The code.

  1. Import the Microsoft Exchange Services.
    1. using Microsoft.Exchange.WebServices.Data;   
  2. Create the instance and pass the credentials.
    1. exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);   
    2. exchange.Credentials = new WebCredentials("USERNAME""PASSWORD""DOMAIN");   
    3. //exchange.Credentials = new WebCredentials("julian", "mypassword", "mydomain");   
    4. exchange.AutodiscoverUrl("EMAILADDRESS");   
    5. //exchange.AutodiscoverUrl("[email protected]");   
    Use ExchangeVersion.Exchange2007_SP1 is your Exchange Server Version is 2007.

    The following is the list with compatible versions.

    Exchange2007_SP1 Exchange Server 2007 Service Pack 1 (SP1).
    Exchange2010 Exchange Server 2010.
    Exchange2010_SP1 Exchange Server 2010 Service Pack 1 (SP1).
    Exchange2010_SP2 Exchange Server 2010 Service Pack 2 (SP2).
    Exchange2013 Exchange Server 2013.
    Exchange2013_SP1 Exchange Server 2013 Service Pack 1 (SP1).

    If everything is correct you should be connected to the Exchange Server.

  3. Read the emails.
    1. TimeSpan ts = new TimeSpan(0, -1, 0, 0);  
    2. DateTime date = DateTime.Now.Add(ts);  
    3. SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);  
    4.   
    5. if (exchange != null)   
    6. {  
    7.     FindItemsResults < Item > findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));  
    8.   
    9.     foreach(Item item in findResults)   
    10.     {  
    11.   
    12.         EmailMessage message = EmailMessage.Bind(exchange, item.Id);  
    13.         ListViewItem listitem = new ListViewItem(new[]   
    14.         {  
    15.             message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Yes" : "No"), message.Id.ToString()  
    16.         });  
    17.         lstMsg.Items.Add(listitem);  
    18.     }  
    19.     if (findResults.Items.Count <= 0)   
    20.     {  
    21.   
    22.         lstMsg.Items.Add("No Messages found!!");  
    23.   
    24.     }  
    25. }  
    The preceding code creates a date of 1 hour before. The Exchange SearchFilter creates a filter to retrieve all the emails received 1 hour ago.

    The FindItemResults retrieves all emails from the Inbox folder applying the filter. Each email is then read inside a loop. The EmailMessage object is created with each retrieved Item.Id.

    The Email Message Details are shown in the ListView.

  4. Read the attachment.
    1. EmailMessage message = EmailMessage.Bind(exchange, new ItemId(msgid));  
    2. if (message.HasAttachments && message.Attachments[0] is FileAttachment)   
    3. {  
    4.     FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;  
    5.     fileAttachment.Load(@  
    6.     "C:\\Users\\Admin\\Documents\\Visual Studio 2012\\Projects\\ReadMailFromExchangeServer\\ReadMailFromExchangeServer\\Attachments\\" + fileAttachment.Name);  
    7.     lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;  
    8. }   
    9. else   
    10. {  
    11.     MessageBox.Show("No Attachments found!!");  
    12. }  
    Read the EmailMessage using message id.

    If the message has an attachment, create the FileAttachment object and then download it.

    Please click here for a complete Video Tutorial

  5. Here's the complete code.
    1. using Microsoft.Exchange.WebServices.Data;  
    2. using System;  
    3. using System.Collections.Generic;  
    4. using System.ComponentModel;  
    5. using System.Data;  
    6. using System.Drawing;  
    7. using System.Linq;  
    8. using System.Net.Sockets;  
    9. using System.Text;  
    10. using System.Threading.Tasks;  
    11. using System.Windows.Forms;  
    12.   
    13. namespace ReadMailFromExchangeServer   
    14. {  
    15.     public partial class Form1: Form   
    16.     {  
    17.         ExchangeService exchange = null;  
    18.   
    19.         public Form1()   
    20.         {  
    21.             InitializeComponent();  
    22.             lstMsg.Clear();  
    23.             lstMsg.View = View.Details;  
    24.             lstMsg.Columns.Add("Date", 150);  
    25.             lstMsg.Columns.Add("From", 250);  
    26.             lstMsg.Columns.Add("Subject", 400);  
    27.             lstMsg.Columns.Add("Has Attachment", 50);  
    28.             lstMsg.Columns.Add("Id", 100);  
    29.             lstMsg.FullRowSelect = true;  
    30.   
    31.         }  
    32.   
    33.         private void btnRead_Click(object sender, EventArgs e)   
    34.         {  
    35.             ConnectToExchangeServer();  
    36.             TimeSpan ts = new TimeSpan(0, -1, 0, 0);  
    37.             DateTime date = DateTime.Now.Add(ts);  
    38.             SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);  
    39.   
    40.             if (exchange != null)   
    41.             {  
    42.                 FindItemsResults < Item > findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));  
    43.   
    44.                 foreach(Item item in findResults)   
    45.                 {  
    46.   
    47.                     EmailMessage message = EmailMessage.Bind(exchange, item.Id);  
    48.                     ListViewItem listitem = new ListViewItem(new[]   
    49.                     {  
    50.                         message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Yes" : "No"), message.Id.ToString()  
    51.                     });  
    52.                     lstMsg.Items.Add(listitem);  
    53.                 }  
    54.                 if (findResults.Items.Count <= 0)   
    55.                 {  
    56.                     lstMsg.Items.Add("No Messages found!!");  
    57.   
    58.                 }  
    59.             }  
    60.   
    61.         }  
    62.   
    63.         public void ConnectToExchangeServer()   
    64.         {  
    65.   
    66.             lblMsg.Text = "Connecting to Exchange Server..";  
    67.             lblMsg.Refresh();  
    68.             try   
    69.             {  
    70.                 exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);  
    71.                 exchange.Credentials = new WebCredentials("USERNAME""PASSWORD""DOMAIN");  
    72.                 exchange.AutodiscoverUrl("USERNAME@DOMAIN");  
    73.   
    74.                 lblMsg.Text = "Connected to Exchange Server : " + exchange.Url.Host;  
    75.                 lblMsg.Refresh();  
    76.   
    77.             }   
    78.             catch (Exception ex)  
    79.             {  
    80.                 lblMsg.Text = "Error Connecting to Exchange Server!!" + ex.Message;  
    81.                 lblMsg.Refresh();  
    82.             }  
    83.   
    84.         }  
    85.   
    86.         private void btnLoad_Click(object sender, EventArgs e)   
    87.         {  
    88.             if (exchange != null)   
    89.             {  
    90.                 if (lstMsg.Items.Count > 0)   
    91.                 {  
    92.                     ListViewItem item = lstMsg.SelectedItems[0];  
    93.   
    94.                     if (item != null)   
    95.                     {  
    96.                         string msgid = item.SubItems[4].Text.ToString();  
    97.                         EmailMessage message = EmailMessage.Bind(exchange, new ItemId(msgid));  
    98.                         if (message.HasAttachments && message.Attachments[0] is FileAttachment)   
    99.                         {  
    100.                             FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;  
    101.                             //Change the below Path   
    102.                             fileAttachment.Load(@  
    103.                             "C:\\Users\\Admin\\Documents\\Visual Studio 2012\\Projects\\ReadMailFromExchangeServer\\ReadMailFromExchangeServer\\Attachments\\" + fileAttachment.Name);  
    104.                             lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;  
    105.                         }   
    106.                         else   
    107.                         {  
    108.                             MessageBox.Show("No Attachments found!!");  
    109.                         }  
    110.                     }   
    111.                     else   
    112.                     {  
    113.                         MessageBox.Show("Please select a Message!!");  
    114.                     }  
    115.                 }   
    116.                 else   
    117.                 {  
    118.                     MessageBox.Show("Messages not loaded!!");  
    119.                 }  
    120.                   
    121.             }   
    122.             else   
    123.             {  
    124.                 MessageBox.Show("Not Connected to Mail Server!!");  
    125.             }  
    126.         }  
    127.   
    128.         private void Form1_Load(object sender, EventArgs e)   
    129.         {  
    130.   
    131.         }  
    132.   
    133.   
    134.     }  
    135. }  

Up Next
    Ebook Download
    View all
    Learn
    View all