Using SendGrid for Email

Email can be a pain in the gazoo. Your code works, you've set up dovecot and postfix correctly, and email recipients... are not receiving emails from your application. The most common cause of failure, of course, is spam filters. Depending on the nature of the spam filter, the email might be automatically deleted!


The key to avoiding this sort of problem is ensuring that your emails never get classified as spam. There are many services that help with this, but the one I selected was SendGrid. Signup was a breeze. They have two different APIs, one for using SMTP and one using web services. SendGrid recommends using SMTP, but I want to get away from having email on my servers at all.

The only difficulty in using SendGrid was their PHP documentation (, which is simply wrong. The following line is what they show as the last step in sending an email using their object library using web or smtp services.


The problem is that the web and smtp properties do not exist, which results in a fatal error when you try to send web or smtp a send() message.

Making SendGrid work

I can only guess that SendGrid's documentation applied to an earlier version of their library. In any case, after spending a bit of quality time with their code, I was able to make it work.

// In a configuration file
define('SENDGRID_ROOT', '/Users/markf/Source/sendgrid/Sendgrid_loader.php');
define('SENDGRID_USERNAME', 'myusername');
define('SENDGRID_PASSWORD', 'mypassword');


// Create the SendGrid mail object
$email = new SendGrid\Mail();
      ->setSubject('Important Application Notice')
      ->setText('This is a plain text message')
      ->setHtml('<p>This is an HTML message</p>');

// Use the SendGrid Web object to send the email