Read an Exchange inbox with WebServices and C#

In some situations you will need to read mails from mailserver. One of those servers is the Exchange. Reading it is pretty easy with the WebServices. At first you need to add the reference to Microsoft.Exchange.WebServices. After that you can begin to code. All you need are two functions. One to build a connection to the Exchange and the other one to find folder and read them.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
private ExchangeService ConnectToExchage(string UserName, string Password, string Domain, string EmailAddress)
{
 try
 {
  // create a service instance and setup the exchange version
  ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

  // access to the account
  service.Credentials = new WebCredentials(UserName, Password, Domain);
  service.AutodiscoverUrl(EmailAddress);
  service.TraceEnabled = true;
  service.TraceFlags = TraceFlags.All;

  // the instance is ready to use
  return service;
 }
 catch (Exception ex)
 {
  return null;
 }
}

public void readInbox()
{
 // connect to the exchange
 ExchangeService service = ConnectToExchage("<your username>", "<your password>", "<your domain>", "<your emailaddress>");
 
 if (service != null)
 {
  //creates an object that will represent the desired mailbox
  Mailbox mb = new Mailbox("<your emailaddress>");

  //creates a folder object that will point to inbox folder
  FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);

  //this will bind the mailbox you're looking for using your service instance
  Folder inbox = Folder.Bind(service, fid);

  //a filter to find just unread items 
  SearchFilter SF = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
  
  //load items from mailbox inbox folder
  if (inbox != null)
  {
   FindItemsResults<Item> items = inbox.FindItems(SF,new ItemView(100));

   foreach (EmailMessage item in items)
   {                      
    try
    {
     item.Load();     
     // do something with the mailitem     
    }
    catch(Exception)
    {}
   }
  }
 }
}

Comments

Popular posts from this blog

How to support multiple languages in WPF