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?