I'm using Exchange Web Services Managed API 1.1 to connect to Exchange server 2010 and then find out new emails received. Now I want to save a copy of the .msg file to a folder on the disk.
I do not want to use any paid third party to integrate.
Any help will be appreciated.
There is no native support for MSG files using EWS. It's strictly an Outlook format.
The MSG spec is published at http://msdn.microsoft.com/en-us/library/cc463912%28EXCHG.80%29.aspx. It's a little complicated to understand, but do-able. You would need to pull down all of the properties for the message and then serialize it into an OLE structured file format. It's not an easy task.
In the end, you are probably better off going with a 3rd party library otherwise it might be a big task to accomplish.
If you are happy to save into the
.eml
format instead, it can be done very easily just using EWS and no third party libraries. The.eml
file will contain all the same information and can be opened by Outlook in the same way as .msg (and also by other programs).Cleaned up code:
You can download all the attachments using EWS API and C# . Below is the example given:
Above code converts all the attachment into bytes. Once you have bytes, you can convert bytes into your required format. To Convert bytes into files and save in the disk follow the below links: Write bytes to file http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Save-byte-array-to-file.html
This suggestion was posted as a comment by @mack, but I think it deserves its own place as an answer, if for no other reason than formatting and readability of answers vs. comments.
You can easily access the MIME contents of the message through message.MimeContent and save the message as an EML file. The latest (2013 and 2016) versions of Outlook will be able to open EML files directly.
If you still need to convert to the MSG format, you have a few options:
1) MSG file format is documented - it is an OLE store (IStorage) file. See https://msdn.microsoft.com/en-us/library/cc463912(v=exchg.80).aspx
2) Use a third party MSG file wrapper, such as the one from Independentsoft: http://www.independentsoft.de/msg/index.html. Setting all properties that Outlook expects can be challenging.
3) Convert EML file to MSG directly using Redemption:
If you are going from Outlook's EntryID via VSTO (Hex) to EwsID, you need to look here: http://bernhardelbl.wordpress.com/2013/04/15/converting-entryid-to-ewsid-using-exchange-web-services-ews/
Saved me. I kept getting a "Data is corrupt." message.