How to correctly set the From address on email that is sent from your website

A lot of our customers run into trouble with email sent from their websites -- FormMail, or custom code. The problem is that the envelope-from address is often not set. If our customers or the recipients of these incorrectly formatted emails hit reply, sometimes the replies disappear into the ether (well actually they come to us but we can't possibly deal with them all so it's the same thing). More importantly though, if the emails bounce - ie the address it was sent to isn't working - the bounce will go to the web hosting provider - yes we get a lot of these, which leads us to the original internal title of this article "How to Send Email from Websites Without Pissing Off Anchor"

Firstly, a bit of theory.

Messages contain two sections: the headers and the body. The headers most people are familiar with, and contains a To: address, and a From: address, in addition to many other headers. This is analogous to a formal letter in which the sender and recipient are printed on the same page as the message.

In addition to this, the MTA also keeps envelope information, analogous to the envelope that the letter is posted in. This is what the MTA uses when conducting an SMTP transaction, i.e. the MAIL FROM command, and RCPT TO commands use data from the envelope to instruct the destination MTA who the message is from and where to send it.

The envelope sender is marked at the destination by the Return-Path field, and is also the address that will receive bounces to messages from the MTA, if the To: address doesn't exist.

How to do it right

The main problem customers have is that they are not setting the envelope-from address, thinking that merely setting From: will suffice. As noted above, this is not sufficient and bounces will return to the web server, not the place they are expecting.

Directly with Sendmail

You specify the envelope from address with the -f flag to sendmail, e.g.: