EWS only reading my inbox

Our Man in Bananas picture Our Man in Bananas · Mar 11, 2014 · Viewed 12.3k times · Source

I am trying to read a particular email account to find items with attachments that are unread, and have certain words in the subject.

I have the below code that works but only reads my inbox and not the inbox I want to check

static void Main(string[] args)
    {
    ServicePointManager.ServerCertificateValidationCallback=CertificateValidationCallBack;
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);// .Exchange2007_SP1);

    service.UseDefaultCredentials = true;
    service.AutodiscoverUrl("[email protected]"); //, RedirectionUrlValidationCallback); //[email protected]

    ItemView view = new ItemView(1);

    string querystring = "HasAttachments:true Kind:email"; 
    //From:'Philip Livingstone' Subject:'ATTACHMENT TEST' Kind:email";

    // Find the first email message in the Inbox that has attachments. 
    // This results in a FindItem operation call to EWS.
    FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

    foreach (EmailMessage email in results)

        if (email.IsRead == false) // && email.HasAttachments == true
        {
            System.Diagnostics.Debug.Write("Found attachemnt on msg with subject: " + email.Subject);

            // Request all the attachments on the email message. 
            //This results in a GetItem operation call to EWS.
            email.Load(new PropertySet(EmailMessageSchema.Attachments));

            foreach (Attachment attachment in email.Attachments)
            {
                if (attachment is FileAttachment)
...

what do I have to change so that my code will read the messages in the inbox of [email protected]?

Answer

anusiak picture anusiak · Mar 11, 2014

By default your mailbox' inbox folder will be set as root when calling FindItems on ExchangeService object. Assuming your domain account has the necessary permissions to access the other mailbox this below should do the trick. I have ommited the service creation part.

//creates an object that will represent the desired mailbox
Mailbox mb = new Mailbox(@"[email protected]");

//creates a folder object that will point to inbox folder
FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb); 

//this will bind the mailbox you're looking for using your service instance
Folder inbox = Folder.Bind(service, fid);

//load items from mailbox inbox folder
if(inbox != null) 
{
    FindItemsResults<Item> items = inbox.FindItems(new ItemView(100));

    foreach(var item in items)
        Console.WriteLine(item);
}