Search code examples
phpemailspam-prevention

Best Practices for "from" header field in PHP e-mail to prevent marking as spam


I am working on a form that will allow users to send their friends an e-mail. The form will have the following fields:

  • From e-mail
  • To e-mail
  • Subject
  • Body

Ideally, the "from" field in the e-mail header would be the user's entered "From e-mail" address so that the recipient will recognize the sender.

But I assume that setting the "from" field in the header as the user's entered "From e-mail" address would fail SPF validation and increase the chances of e-mails being marked as spam.

What are best practices for:

  1. Allowing the e-mail to appear (to the recipient) to come from the sender's "From e-mail"
  2. Decreasing likelihood of the e-mail being marked as spam.

In a quick spot-check,

  • The NY Times "e-mail article" feature set the "from" field in the header to the sender's e-mail address and ended up in my Yahoo inbox.
  • AddThis set the "from" field in the header to the sender's e-mail address and ended up in my Yahoo spam folder.
  • Delicious set the "from" field in the header to "Delicious" and ended up in my Yahoo inbox.

Solution

  • If your domain name is example.com, the FROM header in your outgoing emails from the form need to be something like info@example.com or noreply@example.com

    Set the REPLY-TO header to the "from" address that your user is inputting in on your form.

    To make the recipient recognize the "FROM" address, you can put the senders name in the FROM header, so when the recipient sees the email come in, it will say something along the lines of "John Smith <noreply@example.com>"

    Since you are using PHP, I suggest you take a look at Swiftmailer. It will help you avoid a lot of common header problems in addition to providing awesome methods for building and formatting your emails.

    Official Swiftmailer Website: http://swiftmailer.org/

    Your code could be as simple as:

    $transport = Swift_MailTransport::newInstance();
    $mailer = Swift_Mailer::newInstance($transport);
    
    $message = Swift_Message::newInstance()
        ->setSubject('This is the subject of your message')
        ->setFrom(array('noreply@example.com' => 'John Smith'))
        ->setReplyTo(array('john.smith@gmail.com' => 'John Smith'))
        ->setTo(array('recipient@example.com'))
        ->setBody('The body of your email goes here.');
    
    $mailer->send($message);