I'm in the process of writing a simple console app that monitors a particular exchange mailbox, and when emails meeting particular criteria are received, the app will download an XML file attachment, and archive the email.
I've connected to EWS OK, and have been able to loop through any emails, but I'm struggling when it comes to create an EmailMessage object which I can use to access the attachments.
In the example code below, the EmailMessage message = EmailMessage.Bind(...)
line executes without error, but doesn't return a valid message so when I access and properties or methods, I get an error: 'Object reference not set to an instance of an object'.
I'm new to C# let alone EWS so I'm struggling to know where to start...
Code Snippet:
public static void FindItems()
{
try
{
ItemView view = new ItemView(10);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
ItemSchema.Subject,
ItemSchema.DateTimeReceived);
findResults = service.FindItems(
WellKnownFolderName.Inbox,
new SearchFilter.SearchFilterCollection(
LogicalOperator.Or,
new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Sales Enquiry")),
view);
log2.LogInfo("Total number of items found: " + findResults.TotalCount.ToString());
foreach (Item item in findResults)
{
log2.LogInfo(item.Id);
EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
Console.WriteLine(message.Subject.ToString());
if (message.HasAttachments && message.Attachments[0] is FileAttachment)
{
FileAttachment fileAttachment = message.Attachments[0] as FileAttachment;
fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);
fileAttachment.Load();
Console.WriteLine("FileName: " + fileAttachment.FileName);
}
}
}
catch (Exception ex)
{
log2.LogError(ex.InnerException);
}
}
My code for accessing the attachments is straight from MSDN so I'm hoping it is there are thereabouts... Any ideas?