This article demonstrates how to use Exchange Webservices (EWS), as found on Exchange 2007 SP1 and going forward, to extract email body, headers and other email related items without using or needed Outlook installed. Note this assumes you are using Visual Studio 2008 and C#.
Steps
- Download and install the EWS assemblies from Exchange Web Services Managed API and install the target version either 32 or 64. Please remember to note the directory which it gets installed to for it is needed later. Of note is that the install directory contains an excellent document Getting Started which has examples that show the capabilities of the web services.
- Create your project in Studio, the below example C# code targets a Console Application.
- Add a reference to Microsoft.Exchange.WebServices by browsing to the directory loaded in step 1 and selecting the Microsoft.Exchange.WebServices.dll. Remember to add using Microsoft.Exchange.WebServices.Data; in your code.
- Add these lines of code to initialize the web service:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" ); service.AutodiscoverUrl( "First.Last@MyCompany.com" );- Line 1 : Create an Exchange Web Service instance specifying that we are targeting a specific version of Exchange.
- Line 3 : You may need to have a service account do your dirty work and this line uncommented out is your key to doing that.
- Line 5 : We don’t specify an Exchange server, but auto discover it. The server may be clustered and this will get the best one for the job. We also specify the account’s mailbox to use.
- Once the service is up and running we can now get the emails found in the box. Here is how we do it:
FindItemsResults<Item> findResults = service.FindItems( WellKnownFolderName.Inbox, new ItemView( 10 ) ); foreach ( Item item in findResults.Items ) Console.WriteLine( item.Subject );
- Line 1 : We call the service to find out about the mailbox.
- Line 2 : We are interested in the inbox only, but we could be interested in the calendar. This is where to specify those items.
- Line 3 : We only want 10 items…change that number for different results
- Line 5: Print out the items, we are only going to show the subject but there are other header items we could show.
- Run the program. If everything goes alright then we have gotten the top ten items of the mailbox.
That should get you started. Again check the Getting Started document which the install dropped into the install folder for more examples!
#1 by foamy on October 20, 2009 - 2:34 am
Quote
Hi,
Great article, helped me a lot
I have a question: I’m using the Credentials property to authenticate before using the AutoDiscoverUrl method, but whenever I do, the mailbox that is returned belongs to the user I specified in the Credentials.
E.g I specify Admin in the Credentials and user@domain.com in the AutoDiscoverUrl method. This will give me the Admin’s Inbox.
How can I specify an Administrator account and still get some other mailbox based on the e-mail address I enter in the AutoDiscoverUrl method?
Hope it makes sense. Thanks again
/foamy
#2 by omegaman on October 20, 2009 - 3:39 pm
Quote
Yes it does make sense and I wrote about it in my new blog article Tribal Knowledge: EWS C# Extract Alternate Email Address’ Mailbox HTH
#3 by foamy on October 21, 2009 - 12:06 am
Quote
Brilliant, that does exacly what I need
You’re a diamond!
#4 by Kenneth Scott on October 28, 2009 - 6:05 am
Quote
If we use the EWS API and have to hard-code the Exchange version (ExchangeVersion.Exchange2007_SP1) – is our code going to break when we upgrade to Exchange 2010?
Thanks-
Kenneth
#5 by omegaman on October 28, 2009 - 3:40 pm
Quote
Update: Yes I verified this with Microsoft it will work. The idea is that 2010 has a version of web services and that it will provide both versions 2010 and 2007 SP1. So older clients will not break
Good question, I haven’t played with 2010 beta to answer that. I should load it up in an Hyper-V virtual on my server and test. I will investigate…
But I believe that specifing ExchangeVersion.Exchange2007_SP1 one is simply saying at a minimum that the process want a version of exchange and if the server is 2010 it simply provides web services at that lower version. Hence older clients won’t break.
#6 by Melanie on March 25, 2010 - 7:50 am
Quote
Hi,
When trying to run the code provided above I get the following error:
“An unhandled exception of type ‘Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException’ occurred in Microsoft.Exchange.WebServices.dll
Additional information: The Autodiscover service could not be located.”
Can you help with this please?
Thanks
#7 by omegaman on March 25, 2010 - 8:48 am
Quote
Exchange must be version 2007 with SP1. Is your exchange that version?
You may want to post this question to the Exchange Server Development forum. HTH
#8 by Predrag on April 8, 2010 - 3:05 am
Quote
Hello.
Is there way to get all emails from all accounts in exchange server? Can I do it if I have admin (system) account credentials?
#9 by omegaman on April 9, 2010 - 6:00 am
Quote
I haven’t tried it. Post the question to the MSDN Exchange Development Forum. GL
#10 by Simon on April 16, 2010 - 6:46 am
Quote
Hello!
I’m doing a project where I have to get all unread e-mails from an inbox and I’ve tried to get this thing to work but I encountered a problem quite soon after starting. The error message I’m getting is this:
“The type ‘System.TimeZoneInfo’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′.”
The two possibilities to this error I’ve come up with is this, I haven’t got any web reference, I couldn’t get the installation of it to work, or the fact that I’m using Windows XP. Do you know what causes the problem and if you do, is there a way working around it?
Thanks and all the best!
Simon
#11 by omegaman on April 19, 2010 - 9:04 am
Quote
Post it to the EWS Exchange forum. That sounds like a C# issue and not EWS. GL
#12 by Simon on April 20, 2010 - 12:19 am
Quote
Alrite!
Cheers!
#13 by Steve Ronald on May 3, 2010 - 11:33 pm
Quote
Connection to the exchange server to read Calendar,
CalendarFolder myCalendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar);
responds:
ErrorMissingEmailAddress
This error indicates that you specified a distinguished folder ID in the request, but the account that made the request does not have a mailbox on the system. In that case, you must supply a Mailbox sub-element under DistinguishedFolderId.
I haven’t a clue how to apply Mailbox sub-element under DistinguisedFolderId
#14 by omegaman on May 4, 2010 - 4:56 am
Quote
Post the question to the MSDN Exchange Development Forum. GL
#15 by McKinney on June 8, 2010 - 3:36 pm
Quote
And here I was thinking I was going to have to break down and use MAPI. Thanks for this article!
#16 by ouTThere on June 10, 2010 - 7:06 pm
Quote
wow, I wish I found this a couple months ago.
I spent hours getting MAPI to work
great stuff
#17 by vikram on July 5, 2010 - 6:22 am
Quote
Hi,
I am doing a project in which I have to read all the bounce e-mail messages sent to a user. I am using EWS web reference from the IIS where Exchange 2007 is deployed. PLease let me know how to send the search to fetch the bounce e-mails which contains some attachment. Actually i want to get the name of the attachment file from the bounce e-mail, update the database that this file ie not sent and delete the found e-mails. please help me.
#18 by SeeeD on July 5, 2010 - 6:25 am
Quote
Thank you so much for the tutorial =)
I’ve lost so much time at the Exchange SDK.
But one thing:
I do not use this method:
service.AutodiscoverUrl( “First.Last@MyCompany.com” );
It needs around 10 seconds, to get the URL.
I’ve saved the URI and wrote it into the URL-Property.
#19 by rajen shrestha on July 8, 2010 - 1:08 am
Quote
How can I move to different folder, out of mail server folder or delete attachement from the exchange mail server?
thanks
#20 by Michael on July 22, 2010 - 4:11 pm
Quote
What if the in box is full?
#21 by OmegaMan on July 23, 2010 - 2:50 pm
Quote
The process can still extract emails…it doesn’t manage the box either by adding or deleting.
#22 by SKY on August 15, 2010 - 11:20 pm
Quote
but the process is working in VS 2008 not in 2005,how can i read all types of mails in VS 2005,can anybody help me….??
#23 by Mahendra Take on September 1, 2010 - 4:43 am
Quote
I am developing an application in which i want to subscribe to
calender item of all the users of exchange server by using administrator credential.
Any help will be appreciated.
#24 by azurekudos on October 14, 2010 - 11:06 am
Quote
Sorry I am bit new…where we have to install .msi in Exchange server
#25 by OmegaMan on October 26, 2010 - 8:40 am
Quote
No…nothing is installed on exchange server to make this work it is all client.
#26 by Andrew on November 15, 2010 - 2:33 pm
Quote
From looking at the soap api, is there not a way to get who the email is from? I see to, cc, but no from. Exchange 2007 environment.
#27 by Pravin on November 16, 2010 - 9:05 am
Quote
Hello Simon,
I got the same error:
“The type ‘System.TimeZoneInfo’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′.”
And I resolved it by adding a reference to System.Core, available in .Net tab.
Just incase this helps someone.
Cheers,
Pravin
#28 by Guy D on November 18, 2010 - 12:07 pm
Quote
Where can I find the Active Directory ID? And by domain do you mean the address I use to login to my email?
#29 by OmegaMan on November 18, 2010 - 4:44 pm
Quote
Active directory ID is the NT Id one uses to log into the corporate domain; yes the email address you use. HTH
#30 by Sanjay Patel on November 19, 2010 - 2:51 am
Quote
i getting Error message while reading mail using URL
“The response received from the service didn’t contain valid XML.”
FindItemsResults findResults = service.FindItems(WellKnownFolderName.SentItems,new ItemView(10));
foreach (Item item in findResults.Items)
Console.WriteLine( item.Subject );
why i get this error
#31 by Jørgen on December 7, 2010 - 8:31 am
Quote
I also Get the “The response received from the service didn’t contain valid XML.”
Has this something to do with the Exchange webservice configuration?
#32 by Nibedita Jena on December 9, 2010 - 3:35 am
Quote
Hi,
I have to connect Exchange Server 2007 SP2 and I’m using Visual Studio 2005 C#.Net. I’m trying to connect by MAPI. But till yet not got any article regarding this. Could You please suggest me the best way to do this? Is there any article which I can refer for it? Please suggest me ASAP. It’s urgent for me.
Thanks in Advance.
Regards,
Nibedita Jena
#33 by ashok on December 15, 2010 - 10:59 pm
Quote
Hi All,
I am trying to download contacts (created in outlook) from exchange server and using WebDAV sql query for the same. I am able to download contact related information but I could not download IM address. The problem here is that the Namespace “urn:schemas:contacts” does not contain IM Address property. Has anyone tried downloading IM address of the contact?
#34 by Anu on January 21, 2011 - 5:18 am
Quote
hi,
I am getting “Bed Gateway” error while trying to read teh inbox data.
at line -> FindItemsResults findResults = service.FindItems( WellKnownFolderName.Inbox, new ItemView( 10 ) );
Please let me know how to getrid of this.
For this to work do we need excchange server permissions? i do have a domain account. I am giving the same account details in the code. but eventhough iam gettin “Bad Gateway” error. Please help me.
I am back of this since 3days.
Thanks in advance.
#35 by vasu on February 24, 2011 - 3:11 am
Quote
Hi, i tried with the
service.AutodiscoverUrl(MyName1@domain.com);
method and i am able to get all the inbox mails.
if i try with
service.AutodiscoverUrl(MyName2@domain.com);
Still it is showing the first user(MyName1@domain.com) inbox mails.
Could you please help me to resolve the issue.
#36 by Tassisto on March 7, 2011 - 7:16 am
Quote
Hi,
I have an account with 2 mailboxes. Your code returns only the default mailbox of my account. Is it possible to select the other mailbox by its name (name = Postvak IT Helpdesk)??? Any help is appreciated.
Thanks in advance.
#37 by Conrad on April 21, 2011 - 5:28 am
Quote
Hi, I received the following error (probably for obvious reasons) but is this because of my access or is there some setting on exchange that needs to be changed? I am after all just access my own mail account.
The request failed. The remote server returned an error: (403) Forbidden.
#38 by PaulE on August 8, 2011 - 3:53 pm
Quote
It would be worth noting that many of the properties of the Item object do not load when the Item object is created through FindItems(…). To read these first-class properties (such as Body), you must call item.Load() first.
#39 by DJ Burb on August 31, 2011 - 10:10 am
Quote
THANK YOU!!!!!! This is just what I needed
#40 by Sudeep on September 20, 2011 - 11:11 pm
Quote
Thank you very much.
One query though. How can i read mails if the exchange server is 2003?
#41 by OmegaMan on September 27, 2011 - 4:21 am
Quote
EWS is only available from Exchange 2007 SP1 or greater. 2003 is not supported.
#42 by Gorgi on December 1, 2011 - 2:36 am
Quote
You anybody please help in reading mail from user defined folder instead of inbox using EWS
#43 by Pritam on February 12, 2012 - 2:41 pm
Quote
can I read my gmail account using ExchangeService class?
Thanks in advance
#44 by OmegaMan on February 12, 2012 - 2:55 pm
Quote
Only if Gmail is using Exchange and has an open exchange web service. Which I doubt.
#45 by Dino on February 29, 2012 - 12:19 pm
Quote
Is there a functionality built-in in EWS to find the reply text in the email? In other words, EmailMessage.body will give you both reply and original message body. Any easy to separate them out so we know what is reply text?
#46 by OmegaMan on March 1, 2012 - 11:49 am
Quote
To my knowledge it does not but check on the exchange forums.
#47 by David on March 1, 2012 - 3:19 pm
Quote
Hello, I just found the answer for which I was looking. The way to remove all the items and subfolders is to use the boolean $true This is the way it should look. $Outbox.Empty([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems ,$true)
#48 by srinivas on March 19, 2012 - 10:46 pm
Quote
i am not able to system.net.networkcredential namespace,how i will get
please give me advice.
#49 by Thomas Agustin on May 22, 2012 - 5:16 am
Quote
HI,
We are planning for calender syn for a business unit, i have calender names and i have to sync the all the calender events to the our data base. How do we achieve the same. What access we should grant to all these calenders? We have created a service account ans account has access to all the calenders. How can we read all the calannders using this sv account ?
#50 by sam on June 21, 2012 - 3:36 pm
Quote
The Autodiscover service could not be located.
i am getting this error.please help me.
i have wasted quite a lot of time behind this.
but i could not solve it.
plssss
#51 by karthik on August 21, 2012 - 4:29 am
Quote
i am getting this error after connecting server
The request failed. The remote server returned an error: (401) Unauthorized
#52 by Beena on October 10, 2012 - 3:14 am
Quote
Hi ,
I am getting the below issue, while i create an appointment
“The request failed. The remote server returned an error: (401) Unauthorized”.
i am using below line to call server account,
service.Credentials = new NetworkCredential(strFromID, strPwd, strDomain);
It would be great help, if anyone faced the similar issue befor and the solution is sharable. Thanks in Advance.
Regards,
Beena Celin T.
#53 by Mr Chris on November 5, 2012 - 8:59 am
Quote
Not sure if anyone else has stumbled on this problem. Had this working fine until recently logging into and managing a couple of email accounts automatically. Then something must of changed and am now getting the following back when I utilise the service.autodiscover :
Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException: Autodiscover blocked a potentially insecure redirection to https://webmail.gilestravel.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.
Anyone else had this issue?
#54 by Mike on January 24, 2013 - 1:21 pm
Quote
I got this working just fine but can’t seem to find a way to retrieve the senders email address? Any thoughts?
#55 by Mike on January 25, 2013 - 9:13 am
Quote
Sorry I found what I was missing. Was not binding the item to an EmailMessage object. All is good now. Thanks for the previous examples they helped tremendously.
#56 by yeshveer on April 4, 2013 - 7:00 am
Quote
Hi All i have one questions
can I read my gmail account using ExchangeService class?
and i am getting an Error message while reading mail using URL
“The response received from the service didn’t contain valid XML.”
email.SendAndSaveCopy();
over here why am i getting this when i am sending an email to myself
Thanks in advance
#57 by OmegaMan on April 9, 2013 - 12:29 pm
Quote
EWS only works with Exchange and cannot read GMAIL.