I have a distribution list which is made up of recipients almost exclusively outside of my organization. Due to issues with one of the recipients mail hosts, they reject all messages with a From
header which originates from outside their network. So if [email protected] sends a message to the list, [email protected] will never receive it. As such I have written a transport agent to modify the From
and Sender
in the P1 and P2 SMTP and Message Envelopes of a mail item to be that of distribution list itself. Everything works fine for the most part.
To make it possible to know who sent the email to the distribution list, I have the transport agent set the Display Name of the P2 Message Envelope to be the real email address of the sender. This works if someone outside my organization sends a email to the list, but does not if the sender is inside my organization. I've tried implementing this as both a RoutingAgent
and a SmtpReceiveAgent
and the behavior is the same. From my logging I can see that the messages are being processed for senders internal to my organization.
Does anyone know what this is not behaving as expected?
public void OnEndOfDataHandler(ReceiveMessageEventSource source, EndOfDataEventArgs eodArgs)
{
MailItem mailItem = eodArgs.MailItem;
EmailMessage message = mailItem.Message;
EnvelopeRecipient distributionList = AddressedToDistributionList(mailItem);
if(distributionList != null)
{
mailItem.FromAddress = distributionList.Address;
if (message.From.DisplayName == message.From.SmtpAddress)
message.From = new EmailRecipient(message.From.SmtpAddress.Replace("@", " at "), distributionList.Address.GetAddress(true));
else
message.From = new EmailRecipient(message.From.DisplayName + " (" + message.From.SmtpAddress.Replace("@", " at ") + ")", distributionList.Address.GetAddress(true));
if (message.Sender.DisplayName == message.Sender.SmtpAddress)
message.Sender = new EmailRecipient(message.Sender.SmtpAddress.Replace("@", " at "), distributionList.Address.GetAddress(true));
else
message.Sender = new EmailRecipient(message.Sender.DisplayName + " (" + message.Sender.SmtpAddress.Replace("@", " at ") + ")", distributionList.Address.GetAddress(true));
}
}
Changing the Display Name won't work because when the message is delivered to the Store Exchange will always resolve the Email address use back the EX Address entry from the GAL. This is by design and you won't be alter this behavior. My suggestion would be your agent you should only act after the expansion of the message (eg look at fork https://msdn.microsoft.com/en-us/library/microsoft.exchange.data.transport.routing.queuedmessageeventsource.fork%28v=exchg.80%29.aspx ) and should only act on those messages that are going to be routed to the problematic destination.