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

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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

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.