Skip to main content

Dealing with Non Delivery Reports with Exchange Web Services

If there was one thing i would change if I could redesign email from the ground up it would have to be NDR's. While these delivery reports are functional in what they do from a user and even an administrative prospective they are horribly disfunctional. While there isn't much you can do around the underlying design of NDR's with a little help from your favourite Exchange API there are certain tasks that can be made more livable.

NDR Overload

If your users are sending and receiving a lot of email they you'll probably find that a number of NDR's are being generated for a vast number of different reasons. A lot of the times the loop will get closed where your user having tryed and failed to decipher what the NDR says gives up and calls the helpdesk. If your sending a copy of NDR's to a central mailbox what can be usefull for everybody concerned is to have a digest list of all the NDR's that have been recieved in a certain time frame this can allow you to do some analysis on why these NDR's are being generated in the first place and be a little proactive if you have a problems that a causing these NDR's such as certain DNS records or maybe your server has being blacklisted or just having the ability to have at your finger tips the NDR that a user received without then having to forward it to you.

Using Some Code

Here's the fun part to get a list of NDR's using EWS you need to use a few different operations. The first is you need to use a FindItem operations with a restriction on the MessageClass to limit the items returns to those of type REPORT.IPM.Note.NDR. To get the body of the NDR which will contain the NDR reason a GetItem request that includes the messagebody is nessasary and then the reason can be parsed out of the body its sperated with # characters so it pretty easy. Other important pieces of information can be pulled at the same time like the original subject ,recipient and senders by using the appropriate Extended mapi properties for those items.

To make this a little more flexbile the code i wrote only checks for unread NDR's and then marks them as read once they have been included in the Digest. The Digest mail is then sent using EWS.

Proccessing Attachments on NDR's

If you have attachments on messages that are being sent and then bounced and included in the NDR and you want to process those attachments this can get a little confusing to deal with but its kind of logical when you see it in action. To download any attachment using EWS you need to know the attachmentID. To get an embeeded attachment its no different but to find that attachment you first need to get the orignial message using a GetAttachment request and then go through the attachment collection on that original message and use a Getattachment again from this embeeded message. I include a routine to do this and download any filebased attachments to the C#.

I've put a download of all these functions here some of the code look like

static List GetNDRs(ExchangeServiceBinding esb, BaseFolderIdType[] biArray)
{

List intFiFolderItems = new List();
try
{

BasePathToElementType[] beAdditionproperties = new BasePathToElementType[5];

PathToExtendedFieldType osOriginalSenderEmail = new PathToExtendedFieldType();
osOriginalSenderEmail.PropertyTag = "0x0067";
osOriginalSenderEmail.PropertyType = MapiPropertyTypeType.String;

PathToExtendedFieldType osOriginalSenderAdrType = new PathToExtendedFieldType();
osOriginalSenderAdrType.PropertyTag = "0x0066";
osOriginalSenderAdrType.PropertyType = MapiPropertyTypeType.String;

PathToExtendedFieldType osOriginalSenderName = new PathToExtendedFieldType();
osOriginalSenderName.PropertyTag = "0x005A";
osOriginalSenderName.PropertyType = MapiPropertyTypeType.String;

PathToExtendedFieldType osOriginalSubject = new PathToExtendedFieldType();
osOriginalSubject.PropertyTag = "0x0049";
osOriginalSubject.PropertyType = MapiPropertyTypeType.String;

PathToExtendedFieldType osOriginalRecp = new PathToExtendedFieldType();
osOriginalRecp.PropertyTag = "0x0074";
osOriginalRecp.PropertyType = MapiPropertyTypeType.String;


beAdditionproperties[0] = osOriginalSenderAdrType;
beAdditionproperties[1] = osOriginalSenderEmail;
beAdditionproperties[2] = osOriginalSenderName;
beAdditionproperties[3] = osOriginalRecp;
beAdditionproperties[4] = osOriginalSubject;

try
{
FindItemType fiFindItemRequest = new FindItemType();
fiFindItemRequest.ParentFolderIds = biArray;
fiFindItemRequest.Traversal = ItemQueryTraversalType.Shallow;
ItemResponseShapeType ipItemProperties = new ItemResponseShapeType();
ipItemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
ipItemProperties.AdditionalProperties = beAdditionproperties;
fiFindItemRequest.ItemShape = ipItemProperties;
RestrictionType ffRestriction = new RestrictionType();

IsEqualToType ieToTypeClass = new IsEqualToType();
PathToUnindexedFieldType itItemType = new PathToUnindexedFieldType();
itItemType.FieldURI = UnindexedFieldURIType.itemItemClass;
ieToTypeClass.Item = itItemType;
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "REPORT.IPM.Note.NDR";
constantType.Item = constantValueType;
ieToTypeClass.Item = itItemType;
ieToTypeClass.FieldURIOrConstant = constantType;

IsEqualToType ieToTypeRead = new IsEqualToType();
PathToUnindexedFieldType rsReadStatus = new PathToUnindexedFieldType();
rsReadStatus.FieldURI = UnindexedFieldURIType.messageIsRead;
ieToTypeRead.Item = rsReadStatus;
FieldURIOrConstantType constantType1 = new FieldURIOrConstantType();
ConstantValueType constantValueType1 = new ConstantValueType();
constantValueType1.Value = "0";
constantType1.Item = constantValueType1;
ieToTypeRead.Item = rsReadStatus;
ieToTypeRead.FieldURIOrConstant = constantType1;

AndType raRestictionAnd = new AndType();
raRestictionAnd.Items = new SearchExpressionType[2];
raRestictionAnd.Items[0] = ieToTypeClass;
raRestictionAnd.Items[1] = ieToTypeRead;

ffRestriction.Item = raRestictionAnd;
fiFindItemRequest.Restriction = ffRestriction;

FindItemResponseType frFindItemResponse = esb.FindItem(fiFindItemRequest);
if (frFindItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{
foreach (FindItemResponseMessageType firmtMessage in frFindItemResponse.ResponseMessages.Items)
{
Console.WriteLine("Number of Items Found : " + firmtMessage.RootFolder.TotalItemsInView);
if (firmtMessage.RootFolder.TotalItemsInView > 0)
{
foreach (ItemType miMailboxItem in ((ArrayOfRealItemsType)firmtMessage.RootFolder.Item).Items)
{
GetItemType giGetItem = new GetItemType();
giGetItem.ItemIds = new BaseItemIdType[1] { miMailboxItem.ItemId };
giGetItem.ItemShape = new ItemResponseShapeType();
giGetItem.ItemShape.AdditionalProperties = beAdditionproperties;
giGetItem.ItemShape.BaseShape = DefaultShapeNamesType.Default;
giGetItem.ItemShape.BodyType = BodyTypeResponseType.Text;
giGetItem.ItemShape.BodyTypeSpecified = true;
GetItemResponseType giResponse = esb.GetItem(giGetItem);
if (giResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
{
Console.WriteLine("Error Occured");
Console.WriteLine(giResponse.ResponseMessages.Items[0].MessageText);
}
else
{
ItemInfoResponseMessageType rmResponseMessage = giResponse.ResponseMessages.Items[0] as ItemInfoResponseMessageType;
intFiFolderItems.Add(rmResponseMessage.Items.Items[0]);
// Create an object of update item type
UpdateItemType updateItemType = new UpdateItemType();
updateItemType.ConflictResolution = ConflictResolutionType.AlwaysOverwrite;
updateItemType.MessageDisposition = MessageDispositionType.SaveOnly;
updateItemType.MessageDispositionSpecified = true;
updateItemType.ItemChanges = new ItemChangeType[1];
ItemChangeType changeType = new ItemChangeType();

changeType.Item = rmResponseMessage.Items.Items[0].ItemId;
changeType.Updates = new ItemChangeDescriptionType[1];

// Create a set item field to identify the type of update
SetItemFieldType setItemEmail = new SetItemFieldType();

PathToUnindexedFieldType epExPath = new PathToUnindexedFieldType();
epExPath.FieldURI = UnindexedFieldURIType.messageIsRead;

MessageType mtMessage = new MessageType();
mtMessage.IsRead = true;
mtMessage.IsReadSpecified = true;

setItemEmail.Item = epExPath;
setItemEmail.Item1 = mtMessage;

changeType.Updates[0] = setItemEmail;
updateItemType.ItemChanges[0] = changeType;
// Send the update item request and receive the response
UpdateItemResponseType updateItemResponse = esb.UpdateItem(updateItemType);
if (updateItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{
Console.WriteLine("Update Successful");
}
else
{
Console.WriteLine(updateItemResponse.ResponseMessages.Items[0].MessageText.ToString());
}

}

}
}


}
}
else
{
Console.WriteLine("Error During FindItem request : " + frFindItemResponse.ResponseMessages.Items[0].MessageText.ToString());
}

}
catch (Exception exException)
{
Console.WriteLine(exException.ToString());
// return exException.ToString();
}
return intFiFolderItems;

}
catch (Exception exException)
{
Console.WriteLine(exException.ToString());
// return exException.ToString();
}
return intFiFolderItems;

}

Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.