Sending mail in PHP with Zend and Sendgrid

Posted: September 29th, 2010 | Author: Laurie | Filed under: frameworks, php, sendgrid, zend | 1 Comment »

I use the Zend Framework and quite like it, but the documentation is pretty bad sometimes. In particular, the documentation of their Zend_Mail class is too simple, and the API docs totally unhelpful. So I thought I’d write down what worked for me.

We use Sendgrid to handle our email delivery. It does all the tedious signing and things that are necessary to avoid getting caught in spam traps, which is a huge time-saver. It uses plain authentication, which is a little odd, but it works. Here’s the full code:

set_include_path(
				dirname(__FILE__) . PATH_SEPARATOR .
				get_include_path() . PATH_SEPARATOR .
				'/usr/share/php5'
				);

require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();

$mailConfig = array(
			'host'						=> "smtp.sendgrid.net",
			'port'						=> 25,
			'domain'					=> "your.domain.name",
			'authentication'	=> "plain",
			'username'				=> "youremail@your.domain.name",
			'password'				=> "yoursendgridpassword"
);

$transport = new Zend_Mail_Transport_Smtp(
				$mailConfig['host'],
				array(
						'port' => $mailConfig['port'],
						'auth' => $mailConfig['authentication'],
						'username' => $mailConfig['username'],
						'password' => $mailConfig['password']
				)
);
Zend_Mail::setDefaultTransport($transport);

$message = new Zend_Mail();
$message->setFrom('support@your.domain.name','The Almighty Server');
$message->addTo('your.customer@example.com','John Q. Customer');
$message->setSubject('Oh hai');
$message->setBodyText('
Why hello,
This is an email from us.

Regards,
The Almighty Server.
');
$message->send();

Hopefully this is pretty self-explanatory.