9
votes

I am trying to use the following code to connect and download an attachment from email in an inbox using C# and Exchange Web Services but I am getting a 'System.ArgumentOutOfRangeException' error and I cant see why. I have googled for an answer but i cant find one or the answers I find are for very old versions of EWS.

I know that the rest of the code generally works as I can access other information relating to the email, just not access the attachment.

Cany anyone show me the error of my ways?

Thanks in advance,

James

    static void Main(string[] args)
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        service.Credentials = new NetworkCredential("MYLOGIN", "MYPASSWORD", "MYDOMAIN");

        service.Url = new Uri("https://MYMAILSERVER/EWS/Exchange.asmx");

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(1000));

        foreach (Item item in findResults.Items)
        {
            if (item.HasAttachments && item.Attachments[0] is FileAttachment)
            {
                FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;
                fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);
            }

        }
    }
}

Solved but new problem

I have sorted the issue now by changing the 'foreach (Item item in findResults.Items)' to 'foreach (EmailMessage item in findResults.Items)' but now I need to find out how to enumerate through the attachments - any ideas anyone?

5
Where do you get the exception? What argument is out of range? That information is normally part of the exception.Martin Liversage
it was an out of index error. I have sorted the issue now by changing the 'foreach (Item item in findResults.Items)' to 'foreach (EmailMessage item in findResults.Items)'Jimbo James
The "InnerException" part of the Exception may be worth a look to get that kinda of info tooDaniel Frear

5 Answers

7
votes

Check your profile. If you're running on light mode, attachments are not being downloaded with message.

add following line

item.Load() // loads the entire message with attachment
2
votes

The answer to your new problem is

    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

    //service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );

    service.AutodiscoverUrl("[email protected]");

        FindItemsResults<Item> findResults = service.FindItems(
           WellKnownFolderName.Inbox,
           new ItemView(10));

        foreach (Item item in findResults.Items)
        {
            Console.WriteLine(item.Subject);
            item.Load();
            if(item.HasAttachments)
            {
                foreach (var i in item.Attachments)
                {
                    FileAttachment fileAttachment = i as FileAttachment;
                    fileAttachment.Load();
                    Console.WriteLine("FileName: " + fileAttachment.Name);

                }
            }

        }
1
votes

Unless I'm missing something obvious all you need to do is enumerable through item.Attachments.

Click here and scroll down to where you see the Example heading.

1
votes

Solution for downloading all attachments from specified amount of emails:

  ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
  service.Credentials = new NetworkCredential("login", "password");

  service.Url = new Uri("https://mail.Yourservername.com/EWS/Exchange.asmx");

  ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

  FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));

  if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
      foreach (EmailMessage item in findResults)
       {
         EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
           foreach (Attachment attachment in message.Attachment
             {
               if (attachment is FileAttachment)
                  {
                    FileAttachment fileAttachment = attachment as FileAttachment;      
                    fileAttachment.Load(@"Folder\file.name");
                   }
             }
        }

Don't forget to pass correct version of Exchange Server to ExchangeService constructor.

0
votes

This is a method GetAttachmentsFromEmail that you can use to download attachments.

public static void GetAttachmentsFromEmail(ExchangeService service, ItemId itemId)
    {
        // Bind to an existing message item and retrieve the attachments collection.
        // This method results in an GetItem call to EWS.
        EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));

        // Iterate through the attachments collection and load each attachment.
        foreach (Attachment attachment in message.Attachments)
        {
            if (attachment is FileAttachment)
            {
                FileAttachment fileAttachment = attachment as FileAttachment;

                // Load the attachment into a file.
                // This call results in a GetAttachment call to EWS.
                fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);

                Console.WriteLine("File attachment name: " + fileAttachment.Name);
            }
            else // Attachment is an item attachment.
            {
                ItemAttachment itemAttachment = attachment as ItemAttachment;

                // Load attachment into memory and write out the subject.
                // This does not save the file like it does with a file attachment.
                // This call results in a GetAttachment call to EWS.
                itemAttachment.Load();

                Console.WriteLine("Item attachment name: " + itemAttachment.Name);
            }
        }
    }