Tuesday, November 04, 2008

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;

}

5 comments:

David said...

Hi Glen,

I was unable to download the code at http://msgdev.mvps.org/exdevblog/ndrdigestsxc#.zip.

Please advise.
Thanks

Anonymous said...

Hi Glen,

I also was not able to download this. Sure hope you can get it available, it sounds like something I've been needing for some time now.

Thanks,
Kpeakman@hotmail.com

Glen said...

Sorry try this link instead

http://msgdev.mvps.org/exdevblog/ndrdigestsxc.zip

Cheers
Glen

Anonymous said...

What is this?
using NDR_WebService.ews;

I have a problem using this library because I can't find it

Raj Verma said...

You have nice blog on email delivery service. Thanks for sharing very informative details on email delivery service.

https://pepipost.com/
Email delivery service
Integrations
Webhooks
what are webhooks

Thanks