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
- Microsoft Exchange WebServices (we can install it from NuGet Package Manager).
- Valid Microsoft Exchange Server User Account.
- 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 |
Step 4
The code.
- Import the Microsoft Exchange Services.
- using Microsoft.Exchange.WebServices.Data;
- Create the instance and pass the credentials.
- exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
- exchange.Credentials = new WebCredentials("USERNAME", "PASSWORD", "DOMAIN");
-
- exchange.AutodiscoverUrl("EMAILADDRESS");
-
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.
- Read the emails.
- TimeSpan ts = new TimeSpan(0, -1, 0, 0);
- DateTime date = DateTime.Now.Add(ts);
- SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
-
- if (exchange != null)
- {
- FindItemsResults < Item > findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
-
- foreach(Item item in findResults)
- {
-
- EmailMessage message = EmailMessage.Bind(exchange, item.Id);
- ListViewItem listitem = new ListViewItem(new[]
- {
- message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Yes" : "No"), message.Id.ToString()
- });
- lstMsg.Items.Add(listitem);
- }
- if (findResults.Items.Count <= 0)
- {
-
- lstMsg.Items.Add("No Messages found!!");
-
- }
- }
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.
- Read the attachment.
- EmailMessage message = EmailMessage.Bind(exchange, new ItemId(msgid));
- if (message.HasAttachments && message.Attachments[0] is FileAttachment)
- {
- FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
- fileAttachment.Load(@
- "C:\\Users\\Admin\\Documents\\Visual Studio 2012\\Projects\\ReadMailFromExchangeServer\\ReadMailFromExchangeServer\\Attachments\\" + fileAttachment.Name);
- lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;
- }
- else
- {
- MessageBox.Show("No Attachments found!!");
- }
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
Here's the complete code.
- using Microsoft.Exchange.WebServices.Data;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
-
- namespace ReadMailFromExchangeServer
- {
- public partial class Form1: Form
- {
- ExchangeService exchange = null;
-
- public Form1()
- {
- InitializeComponent();
- lstMsg.Clear();
- lstMsg.View = View.Details;
- lstMsg.Columns.Add("Date", 150);
- lstMsg.Columns.Add("From", 250);
- lstMsg.Columns.Add("Subject", 400);
- lstMsg.Columns.Add("Has Attachment", 50);
- lstMsg.Columns.Add("Id", 100);
- lstMsg.FullRowSelect = true;
-
- }
-
- private void btnRead_Click(object sender, EventArgs e)
- {
- ConnectToExchangeServer();
- TimeSpan ts = new TimeSpan(0, -1, 0, 0);
- DateTime date = DateTime.Now.Add(ts);
- SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
-
- if (exchange != null)
- {
- FindItemsResults < Item > findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));
-
- foreach(Item item in findResults)
- {
-
- EmailMessage message = EmailMessage.Bind(exchange, item.Id);
- ListViewItem listitem = new ListViewItem(new[]
- {
- message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Yes" : "No"), message.Id.ToString()
- });
- lstMsg.Items.Add(listitem);
- }
- if (findResults.Items.Count <= 0)
- {
- lstMsg.Items.Add("No Messages found!!");
-
- }
- }
-
- }
-
- public void ConnectToExchangeServer()
- {
-
- lblMsg.Text = "Connecting to Exchange Server..";
- lblMsg.Refresh();
- try
- {
- exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
- exchange.Credentials = new WebCredentials("USERNAME", "PASSWORD", "DOMAIN");
- exchange.AutodiscoverUrl("USERNAME@DOMAIN");
-
- lblMsg.Text = "Connected to Exchange Server : " + exchange.Url.Host;
- lblMsg.Refresh();
-
- }
- catch (Exception ex)
- {
- lblMsg.Text = "Error Connecting to Exchange Server!!" + ex.Message;
- lblMsg.Refresh();
- }
-
- }
-
- private void btnLoad_Click(object sender, EventArgs e)
- {
- if (exchange != null)
- {
- if (lstMsg.Items.Count > 0)
- {
- ListViewItem item = lstMsg.SelectedItems[0];
-
- if (item != null)
- {
- string msgid = item.SubItems[4].Text.ToString();
- EmailMessage message = EmailMessage.Bind(exchange, new ItemId(msgid));
- if (message.HasAttachments && message.Attachments[0] is FileAttachment)
- {
- FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
-
- fileAttachment.Load(@
- "C:\\Users\\Admin\\Documents\\Visual Studio 2012\\Projects\\ReadMailFromExchangeServer\\ReadMailFromExchangeServer\\Attachments\\" + fileAttachment.Name);
- lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;
- }
- else
- {
- MessageBox.Show("No Attachments found!!");
- }
- }
- else
- {
- MessageBox.Show("Please select a Message!!");
- }
- }
- else
- {
- MessageBox.Show("Messages not loaded!!");
- }
-
- }
- else
- {
- MessageBox.Show("Not Connected to Mail Server!!");
- }
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
-
- }
-
-
- }
- }