Search code examples
c#exchangewebservices

Daily download of attachements from mailbox


I want to check a mailbox daily and download the attachements of all mails. For now I just can do this for one email when i set the ItemId manually. My foreach loop is not running. I am getting a System.ArgumentOutOfRangeException in the loop at:

FileAttachment attachment = message.Attachments[0] as FileAttachment;

In the XML I can clearly see that the ItemId is correct and there's an attachement as well.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

service.Credentials = new NetworkCredential("user", "pwd", "domain");

service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;

service.Url = new Uri("https://fqdn_of_server/EWS/exchange.asmx");

PropertySet itempropertyset = new PropertySet(BasePropertySet.IdOnly, ItemSchema.HasAttachments);

ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults;
view.PropertySet = itempropertyset;

SearchFilter searchFilter = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-1));

findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

foreach (EmailMessage message in findResults)
{
    EmailMessage.Bind(service, new ItemId(message.Id.ToString()), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
    FileAttachment attachment = message.Attachments[0] as FileAttachment;
    FileAttachment fileAttachment = attachment as FileAttachment;
    fileAttachment.Load();
    fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);
}

I am using ews v2.0.50727

EDIT___________

This code for one specific email is working fine. But I can't adapt this to a loop. So I guess this is a problem with my query for just the daily mails.

EmailMessage message = EmailMessage.Bind(service, new ItemId("AAMkADM1MWIyYjA4LWViNDEtNGQ2OS1hMDlkLTdiMDY2YTU0Y2MzMwBGAAAAAABO/r/HLJjWR6+SA9a3YgeTBwDUar3a2c6dRJoGCSVHCKVoAAAARWONAADUar3a2c6dRJoGCSVHCKVoAAAAYCsXAAA="), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

foreach (Attachment attachment in message.Attachments)
    {
        Debug.WriteLine("Attachement: " + attachment);
        if (attachment is FileAttachment)
        {
            FileAttachment fileAttachment = attachment as FileAttachment;
            Debug.WriteLine("Attachement: " + attachment);

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

            // Load attachment contents into a file.
            fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);

            // Stream attachment contents into a file.
            FileStream theStream = new FileStream("C:\\temp\\Stream_" + 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();
            Debug.WriteLine("Attachement: " + attachment);
            Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
        }
    }

Solution

  • Found the solution. i thinkt the problem was the itempropertyset.

    Here is the working code:

    using System;
    using Microsoft.Exchange.WebServices.Data;
    using System.Net;
    using System.IO;
    using System.Diagnostics;
    
    namespace EWS_API
    {
        class Program
        {
            static void Main(string[] args)
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange010_SP);
    
                service.Credentials = new NetworkCredential("user", "pwd", "domain");
    
                service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;
    
                // ignore certificate errors
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
    
                // set ews uri without autodiscover (just for internal use)
                service.Url = new Uri("https://fqdn_server/EWS/exchange.asmx");
    
                // filter for only daily mails
                SearchFilter searchFilter = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-1));
    
                ItemView itemView = new ItemView(int.MaxValue);
                FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, itemView);
    
                if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
                    foreach (Item item in findResults.Items)
                    {
                        EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                        foreach (Attachment attachment in message.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();
                                fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);
                            }
                        }
                        Debug.WriteLine(item.Subject);
                    }
                else
                    Debug.WriteLine("no items");
            }
        }
    }