Reputation: 55
I would like to get all messages.BodyText in my email. I have already some code, tried many things, but didn't catch what really will work.
My code:
ExchangeService service;
service = new ExchangeService
{
Credentials = new WebCredentials("mail.com", @"password")
};
List<String> items = new List<String>();
// This is the office365 webservice URL
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ItemView view = new ItemView(50);
FindItemsResults<Item> Items = service.FindItems(WellKnownFolderName.Inbox, view); // line 34
// 'Object reference not set to an instance of an object.' / on line 34
foreach (Item item in Items)
{
if (item is EmailMessage)
{
item.Load();
string subject = item.Subject;
string mailMessage = item.Body;
}
items.Add(item.TextBody); // line 44
//You must load or assign this property before you can read its value / on line 44
}
foreach (var item in items)
{
Console.WriteLine(item);
}
When I'm trying to run my code, then I got two errors:
The second error is working from time to time, I'm not sure what is wrong.
Thank you in advance!
Upvotes: 1
Views: 1259
Reputation: 22032
If you want the Text body of the message then you need to use a propertyset that will specifically request that. A message may not have a Text body so in that instance the Exchange store will do an on the fly conversion what you code should look like is
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties)
{
RequestedBodyType = BodyType.Text
};
foreach (Item item in Items)
{
if (item is EmailMessage)
{
item.Load(psPropSet);
string subject = item.Subject;
string mailMessage = item.Body;
}
items.Add(item.TextBody);
}
Keep in mind this will make a call to the Exchange server every time you call Load which is really inefficient and done on a large scale will mean you code with be throttled. This can be batched using LoadPropertiesForItems in EWS eg https://learn.microsoft.com/en-us/answers/questions/614111/processing-120k-emails-takes-more-than-a-day-using.html
Upvotes: 1
Reputation: 747
Try calling the load method before attempting to assign a value.
In your code here:
foreach (Item item in Items)
{
if (item is EmailMessage)
{
item.Load();
string subject = item.Subject;
string mailMessage = item.Body;
}
items.Add(item.TextBody); // line 44
//You must load or assign this property before you can read its value / on line 44
}
You are checking if an item is EmailMessage. There may be some in the list that are not an EmailMessage which would cause them to be accessed before using the Load method.
You could try putting the item load outside of the conditional and that would most likely fix the issue.
Please see this question here: Error when I try to read/update the .Body of a Task via EWS Managed API - "You must load or assign this property before you can read its value."
Upvotes: 0