Arturito.net

Come to The Dark Side, We Have Cookies!

Accesing shared mailbox in Exchange Web Services 2007 Service Pack 1 and downloading attachments with C#

with 2 comments

In one of the previous articles I presented a sample code which allows to download attachments from email in Microsoft Exchange Server 2003 using WebDAV.
However, with Microsoft exchange 2007 it can be achieved by using Exchange Web Service (EWS). In order to authenticate, user requires
webmail access. Here is the sample code that allows to access mail resources of the shared mailbox.
	    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            NetworkCredential cred = new NetworkCredential("username", "password", "domain");
            Uri url = new Uri(@"https://server/EWS/Exchange.asmx");
            service.Url = url;
            service.Credentials = cred;

            //Mailbox mb = new Mailbox("artur.kedzior@ext.oami.europa.eu");
            Mailbox mb = new Mailbox("sharedmailbox@yourcompany.com");

            FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb);

            // Add a search filter that searches on the body or subject.
            List<searchFilter> searchFilterCollection = new List<searchFilter>();
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Financial Reports"));
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());

            // Create a view with a page size of 10.
            ItemView view = new ItemView(10);

            // Identify the Subject and DateTimeReceived properties to return.
            // Indicate that the base property will be the item identifier
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);

            // Order the search results by the DateTimeReceived in descending order.
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

            // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
            view.Traversal = ItemTraversal.Shallow;

            FindItemsResults<item> findResults = service.FindItems(fid1, searchFilter,view);
            foreach (Item item in findResults.Items)
            {
                EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

                foreach (Attachment attachment in message.Attachments)
                {
                    if (attachment is FileAttachment)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;

                        // Load the file attachment into memory and print out its file name.
                        fileAttachment.Load();
                        Console.WriteLine("Attachment name: " + fileAttachment.Name);

                        // Stream attachment contents into a file.
                        FileStream theStream = new FileStream("D:\\Downloads\\Attachments\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        fileAttachment.Load(theStream);
                        theStream.Close();
                        theStream.Dispose();
                    }
                    else // Attachment is an item attachment.
                    {
                        // Load attachment into memory and write out the subject.
                        ItemAttachment itemAttachment = attachment as ItemAttachment;
                        itemAttachment.Load();
                        Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
                    }
                }
            }

Written by guru

June 14th, 2010 at 11:37 am

Posted in C sharp

  • CJ

    Hi,

    Thanks for this posting. I had a request from a client of mine. They wanted to filter the attached email by the subject line. Which is the itemAttachment.Item.subject in your code. Then load the file attachment based on the subject line of the attached email to a folder that was named after the subject line. Since the email that they received could have multiple emails attached to them, and each attached email could have multiple attached files asscoiated. I am trying to figure out a way to link the item attachment with the file attachment in the attached email and group them by the item attachment subject.

    Would you please give me some pointers on how to implement this?

    Thanks in advance,

    - CJ

  • arturito

    To be honest I’ve never had a need to do it.

    But you could possibly compare the FileAttachment.ContentId with ItemAttachment.ContentId.

    http://msdn.microsoft.com/en-us/library/dd636130(v=EXCHG.80).aspx

    http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.fileattachment_members(v=EXCHG.80).aspx

    Hope this helps!