marcellus denta
marcellus denta

Reputation: 27

Read Email Outlook 365 folder - EWS

I want to access email in a new folder that i created before called "EIMS" in my Microsoft Exchange.
I just know how to access inbox but I can't access in specific folder.

here is my code in C#:

static void GetInboxMail(string emailAddress, string pass)
{
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
    service.Credentials = new NetworkCredential(emailAddress, pass);

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

    if (service != null)
    {
        FindItemsResults<Item> result = service.FindItems(WellKnownFolderName.Inbox, new ItemView(100));

        foreach (Item item in result)
        {
            EmailMessage message = EmailMessage.Bind(service, item.Id);
            string body = message.Body.Text;
            string from = message.From.Name.ToString();
            string subject = message.Subject.ToString();
            Console.WriteLine("Email Sender :" + from);
            Console.WriteLine("Email Body" + body);
            Console.WriteLine("Email Subject" + subject);
        }
    }
}

Have any suggestions what to add in my code?

Upvotes: 0

Views: 1472

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

You need to first find that TargetFolders FolderId and you can then do a search against that folder. There a few different ways people do this eg a few are outlined in Get to an Exchange folder by path using EWS

The method I always use is to feed in a Path and then a do shallow search to find the target folder eg GetFolderFromPath(service,"[email protected]","\Inbox\folder")

internal static Folder GetFolderFromPath(ExchangeService service,String MailboxName,String FolderPath)
{
    FolderId folderid = new  FolderId(WellKnownFolderName.MsgFolderRoot,MailboxName);   
    Folder tfTargetFolder = Folder.Bind(service,folderid);
    PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties);
    String[] fldArray = FolderPath.Split('\\'); 
    for (Int32 lint = 1; lint < fldArray.Length; lint++) { 
        FolderView fvFolderView = new FolderView(1);
        fvFolderView.PropertySet = psPropset;
        SearchFilter  SfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName,fldArray[lint]); 
        FindFoldersResults findFolderResults = service.FindFolders(tfTargetFolder.Id,SfSearchFilter,fvFolderView); 
        if (findFolderResults.TotalCount > 0){ 
        foreach(Folder folder in findFolderResults.Folders){ 
            tfTargetFolder = folder;                
            } 
        } 
        else{ 
            tfTargetFolder = null;  
            break;  
        }     
    }
    if (tfTargetFolder != null)
    {
        return tfTargetFolder;
    }
    else
    {
        throw new Exception("Folder Not found");
    }
}

Upvotes: 1

Related Questions