Wednesday, 18 December 2013

Microsoft Exchange and Return-path variable

Just recently I had a customer who had to send newsletters generated from a custom application. All e-mails were relayed through their Exchange 2010 server. The problem was that all bounced e-mails not delivered for various reasons were returned to the sender's address. The customer tried to modify Return-path header from the application side so that all bounced e-mails would be returned to a special mailbox from which returned e-mails could be parsed and analyzed.

The problem is that Exchange does not accept Return-path from a client but it automatically applies it to the message using the From header. The solution for the problem is very simple and that is to generate e-mail message with Sender and From fields. The Sender field should be populated with the "bounce-back" e-mail address and the From field with the e-mail address that final recipient should see as a sender of the message. Exchange will then populate the Return-path variable using the Sender field instead of From field.

You can test with this simple powershell script:

  $smtpServer = "some_ip_address"
  $msg = new-object Net.Mail.MailMessage

  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
  $msg.From = "from@email.com"
  $msg.Sender = "sender@email.com"
  $msg.To.Add("some_recipient@domain.com")
  $msg.Subject = "Email Test"

  $msg.Body = "Testing return-path header"
  $smtp.Send($msg)