0
votes

Here is my scenario that I am trying to solve: I have access with my user 'myuser' to a service mailbox 'serviceMail'. So this is not my personal mailbox but another mailbox setup at my company that we have email sent to for various purposes. I know I have access to it, because I have added this mailbox in my Outlook and I am able to check the inbox like I normally for my own email. I am trying to use EWS to write a c# program that will grab the attachments from emails in the 'serviceMail' Inbox. I am getting an "401 Unauthroized Access" when attempting to find items. What am I doing wrong? My code is below.

Here is how I am connecting to the service:

  public ExchangeService ConnectToExchangeServer()
    {



        const string strMailbox = "[email protected]";
        const string strLoginUser = "[email protected]";
        const string strLogingUserpwd = "pwd";
        const string strO365Url = "https://outlook.office365.com/EWS/Exchange.asmx";


        try
        {
            exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            exchange.Credentials = new WebCredentials(strLoginUser, strLogingUserpwd, "sabra.com");
          //  exchange.AutodiscoverUrl(strMailbox,RedirectionUrlValidationCallback);

            exchange.Url = new Uri(strO365Url);

            return exchange;

        }
        catch (Exception ex)
        {
        }

        return exchange;
    }

below is code for trying to find the items

  ExchangeService service = ga.ConnectToExchangeServer();


        TimeSpan ts = new TimeSpan(0, -1, 0, 0);
        DateTime date = DateTime.Now.Add(ts);
        SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

        if (service != null)
        {
            //FindItemsResults<Item> findResults = ga.exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));

            //FindItemsResults<Item> findResults = ga.exchange.FindItems(WellKnownFolderName.Inbox,);

            // Return a single item.
            ItemView view = new ItemView(1);

            string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

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

            foreach (Item item in findResults)
            {

                EmailMessage message = EmailMessage.Bind(ga.exchange, item.Id);
                if (message.HasAttachments && message.Attachments[0] is FileAttachment)
                {
                    FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
                    //Change the below Path   
                    fileAttachment.Load(@"D:\\QlikData\\Lean\\EmailExtract" + fileAttachment.Name);
                    // lblAttach.Text = "Attachment Downloaded : " + fileAttachment.Name;
                }
                else
                {
                    // MessageBox.Show("No Attachments found!!");
                }
            }
            if (findResults.Items.Count <= 0)
            {
                //lstMsg.Items.Add("No Messages found!!");

            }
        }

I get the error "The request failed. The remote server returned an error: (401) Unauthorized." on the FindItemsResults findResults = service.FindItems(WellKnownFolderName.Inbox, querystring, view) line of code.

Any ideas?

1
Are you resolve this issue? I have the same problem on my MacOS.Roma Pavliuk

1 Answers

0
votes

Your code will only access the Inbox of the mailbox of the calling account. You need to use FolderId overload to specify the actual mailbox you want to access. see "Explicit access and the EWS Managed API" in https://msdn.microsoft.com/en-us/library/office/dn641957(v=exchg.150).aspx

You are also specifing the username in the credentials incorrectly eg you should either use the downlevel format netbiosdomain\username or use the UPN https://msdn.microsoft.com/en-us/library/windows/desktop/aa380525(v=vs.85).aspx and omit the domain in that case. see https://social.technet.microsoft.com/Forums/en-US/12de5368-dde0-4d91-a1b2-394c4487d0f1/ews-the-request-failed-the-remote-server-returned-an-error-401-unauthorized?forum=exchangesvrdevelopment