Skip to main content

From Address Rewriting in a Transport Agent for a Exchange 2007 Hub Server

The ability to rewrite the from address of emails can be exceedingly useful if you are working with consolidating or migrating email systems especially if you have two (or more) companies merging or you're trying to consolidate disparate email system across orgs. Exchange 2007 has a great address rewriting agent that runs on a Edge server which is explained in http://technet.microsoft.com/en-us/library/aa996806.aspx. If you aren't implementing an Edge server as part of your Exchange org then unfortunately you cant use this agent on a Hub server. One solution to this is that you write your own agent to do this which is what this post is about. Now that link I just pointed to has some very important information about the fields you should and shouldn't rewrite in an address rewriting Agent and the reason you shouldn't rewrite particular fields. The Return-Path is probably the one of most note and maybe the one people will tend to want to rewrite because of the visibility of the original address in the header and possible SPAM detection issues where the return-path will be different to the From address etc. But it is probably best to leave it as someone has probably done a lot more testing then you at this and it best not to rewrite it the longer story I'm sure is a lot more complicated.

Envelope From (MAIL FROM)


This field can be known more commonly as one of the P1 headers and is available in a Transport event as the mailitem.FromAddress property. To rewrite this address you need to use the RoutingAddress type e.g

e.MailItem.FromAddress = new RoutingAddress("localPart", "newFromDomain");

Body From and Sender

These fields are part of the P2 headers and are exposed via the EmailMessageClass accessable via the MailItem.Message property. Eg to rewrite these properties

e.MailItem.Message.From.SmtpAddress = localPart + "@" + newFromDomain;
e.MailItem.Message.Sender.SmtpAddress = localPart + "@" + newFromDomain;


Body Reply-To

Because there can be more then one address within the Reply-To property you need some code that will loop through the recipients collection and re-map address's as nessasary. e.g

foreach (EmailRecipient rpReplyTo in e.MailItem.Message.ReplyTo) {
if (rpReplyTo.SmtpAddress != null)
{
String rtSourceAddress = rpReplyTo.SmtpAddress.ToString();
String[] rtSourceArray = rtSourceAddress.Split('@');
if (rtSourceArray[1].ToString().ToLower() == oldFromDomain) {
rpReplyTo.SmtpAddress = rtSourceArray[0].ToString() + "@" + newFromDomain;
}
}

Disposition-Notification-To and Return-Receipt-To

These two properties represent Read Recipient address's the reason there are two is a little complicated and has a little to do with history but the one that relates to the RFC and is the standard property is Disposition-Notification-To which is what is exposed by the EmailMessageClass and can be rewritten with something like.


EmailRecipient dnDispNotice = e.MailItem.Message.DispositionNotificationTo;
String dnSourceAddress = dnDispNotice.SmtpAddress.ToString();
String[] dnSourceArray = dnSourceAddress.Split('@');
if (dnSourceArray[1].ToString().ToLower() == oldFromDomain)
{
dnDispNotice.SmtpAddress = dnSourceArray[0].ToString() + "@" + newFromDomain;
}

The second header Return-Receipt-To which is non standard is a little trickier this isn't exposed as a property by the EmailMessageClass but can be accessed as an AddressHeader when looping through the MIME headers. Rewriting this field is difficult in a Transport agent and the only method I've found that works is to use the MIME writer. To simplify my transport agent i took what might prove to be the wrong approach of just deleting this header. I took the view point that its a redundant header anyway and any compliant client should support the standard DispositionNotificationTo header. To delete the header you can use code like.


HeaderList hlHeaderlist = e.MailItem.Message.RootPart.Headers;
AddressHeader mhRrecp = (AddressHeader)hlHeaderlist.FindFirst("Return-Receipt-To");
hlHeaderlist.RemoveChild(mhRrecp);

If you are looking for some code to read an AddressHeader Email value which you wont be able to do by just looping through the headerlist like normal Text headers you need to use some code that looks like.

Stream messageStream = e.MailItem.GetMimeReadStream();
MimeReader mrMimeReader = new MimeReader(e.MailItem.GetMimeReadStream());
mrMimeReader.ReadFirstChildPart();
mrMimeReader.EnableReadingUnparsedHeaders();
while (mrMimeReader.HeaderReader.ReadNextHeader()) {
if (mrMimeReader.HeaderReader.Name.ToString() == "Return-Receipt-To") {
MimeAddressReader reRecp = mrMimeReader.HeaderReader.AddressReader;

};
}

Im nore sure if this is the best method but the documentation for the MIMEReader class is very limited.

Thats it while its not 100% hopefully it will help if your trying to write your own address rewriting Transport Agent.

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 Gr...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...
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.