More Correct Email from CakePHP

One problem a lot of people have with sending email from PHP in general is properly setting the envelope sender of the message, so that it’s correct in all the headers. This is important because it affects spam filtering rather drastically. Also, some ISPs and other email providers won’t even accept a message if the envelope header is set to an invalid address.

In regular PHP, this is simple to fix. Consider the following example, that sets the from address properly:

<?php
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
);
mail(
    "example@example.com", 
    "Test Message", 
    "This is a test message", 
    $headers, 
    "-fwebmaster@example.com"
);

The key here is that last parameter we pass to the function: ‘-fwebmaster@example.com’. That passes a command-line option to sendmail that properly sets the envelope sender. Most people leave that off, because they don’t even realize the need it there.

Okay, so now we know how to do it in raw PHP. How do we do this using CakePHP’s email component? After all, the documentation doesn’t mention anything about that ‘additional parameters’ argument, does it? Or maybe it does. You just have to read the full API docs very carefully. It turns out, if you set the ‘additionalParams’ property of the Email Component, it will pass it on to the mail() function when it calls it. Perfect! So, here’s how to properly initialize the Email Component in CakePHP:

<?php
$this->Email->to = 'example@example.com';
$this->Email->subject = 'Test Message';
$this->Email->replyTo = 'webmaster@example.com';
$this->Email->from = 'webmaster@example.com';
$this->Email->additionalParams = '-fwebmaster@example.com';
$this->Email->template = 'test_message';
$this->Email->sendAs = 'both';

And there you have it! The correct way to send email with proper envelope headers from CakePHP. Enjoy the lower spam score that results!

%d bloggers like this: