Guest post: SendGrid takes the Cake[PHP] when it comes to SMTP


Posted on

The following is a guest blog post from one of our customers and community members, Dave Loftis. Dave is an independent developer, and co-founder of VarVee.com and MyD8.net. You can check out his blog at blog.lofdev.com.

If you’re a PHP developer who is building a large Internet application, or even a small one, using CakePHP, you have undoubtedly taken a look at Cake’s built-in Mail component. The built-in component is simple and powerful, and it works well for most things you might do. It’s really great for sending “welcome-to-X” or “forgot-your-password” emails. But, once you deploy and start using things in the real world, you’re going to run into some very real issues. If someone requests a password reset, they expect that email to arrive to their inbox within seconds. No one wants to search their SPAM filters for a password reminder message from a site they use. And, heaven forbid if you have a few thousand users and want to integrate mailing list management, or track the status of your messages in real time.

So, when you’re ready to really unleash the power of email, you need to **integrate SendGrid** into your application. SendGrid extends the basic SMTP service active on your web host, and it does so in some very clever ways. You can track email delivery, bounce, open, and link click-throughs in real time, and you can fire-once and forget massive email lists, using a mail-merge-like function. Basically, if you do anything with email, you should use SendGrid – but you know that; you’re on their blog!
I’ve been using their service for a couple years, and could not do with out it, so I figured I ought to share how I use SendGrid from CakePHP. When I started, I signed up for SendGrid service, using their free service level, and I simply set my SMTP credentials, and point CakePHP at SendGrid’s SMTP servers.

/* SMTP Options */
$this->Email->smtpOptions = array(
'port'=>'25',
'timeout'=>'30',
'host' => 'smtp.sendgrid.net',
'username'=>'your_sendgrid_username',
'password'=>'your_sendgrid_password',
'client' => 'smtp_helo_hostname'
);

This will get you started, but it won’t enable some of the best features of SendGrid’s service. Using their SMTP API and their Event API, you can track, in real time, delivery, bounces, opens, and clicks for all your emails, on an individual basis. You can also send bulk email to hundreds, or thousands of users, with a single message to SendGrid’s servers.

Getting Started
After you sign up for their service, clone my CakePHP-SendGrid git project (https:// github.com/lofdev/CakePHP-SendGrid) into your /app/controllers/components directory. Then setup your credentials in your database config file (/app/config/ database.php).


class DATABASE_CONFIG {
... // Rest of file
var $sendgrid = array (
'port' => '25',
'timeout' => '30',
'host' => 'smtp.sendgrid.net',
'username' => '',
'password' => '',
'client' => 'smtp_helo_hostname',
'support_email' => ''
);
... // Rest of file
}

It’s that easy. You’re ready to use a wide-swath of SendGrid’s email features.

Use Case #1: Real-time Tracking
To send a single email, with no tracking, your code will look something like this.

$this->SendgridEmail->sendEmail(
array(
'to' => 'to@email.com',
'subject' => 'This is a test',
'from' => 'from@domain.com',
'reply-to' => 'reply-to@domain.com',
'template' => 'template_name.ctp',
'layout-type' => 'both',
)
)

To add tracking features to the email, you will want to build a database table in which to record message recipients, unique identifier, and any other details relevant to your system. You can then change your code to look like this.

$unique_id = your_function_generating_unique_id();
$this->SendgridEmail->sendEmail(
array(
'to' => 'to@email.com',
'subject' => 'This is a test',
'from' => 'from@domain.com',
'reply-to' => 'reply-to@domain.com',
'template' => 'template_name.ctp',
'layout-type' => 'both',
'unique' => $unique_id
)
);

This simply adds a unique identifier to your email message, which SendGrid uses to ping your servers with the email recipient’s address, an action code (opened, clicked, etc), and the unique identifier. All you need to do is write a quick controller to catch these events, and record status messages for each message.
For more information about SendGrid’s EventAPI, check their documentation.

Use Case #2: Bulk Messages
I manage a system with tens of thousands of user with whom I need to communicate. We primarily do this through the use of a large SMS message queue, and a cron job sending and recording each message. It takes a lot of planning and processing power to do this. Communicating with my users over email is trivial, by comparison.
First, I build a template in /app/views/elements/email/text/ template_name.ctp, and insert substitution field placeholders. [Note: I’m only going to show the text email, but you should follow the same technique for your html template.]

Dear -name-,
Your secret code word is -secret-.

Sincerely,
Support Team

I then modify my send function by adding substitution arrays, in which the values to be used in place of the placeholder text are keyed in an array to the placeholder text. Continuing the code from above:

$to_array = array(
'address1@domain.com',
'address2@domain.com',
'address3@domain.com'
);

$name_array = array(
'Alice',
'Bob',
'Carol'
);

$secret_array = array(
'Tomato',
'Apple',
'Crayon'
);

$this->SendgridEmail->sendEmail(
array(
'to' => $to_array,
'subject' => 'This is a test',
'from' => 'from@domain.com',
'reply-to' => 'reply-to@domain.com',
'template' => 'template_name.ctp',
'layout-type' => 'both',
'merge-values' => array(
'-name-' => $name_array,
'-secret-' => $secret_array
)
)
)

I then send an array of email address to the sendEmail function, rather than a single email address. The component adds all the necessary information to a single email message, and SendGrid handles the rest. Dead simple.

Now, SendGrid developer support tells me that it’s not possible to directly combine these two use cases, but I can think of a few ways to do it possibly. It would just take a little bit of hacking, but that’s a story for another day.
For now, go get the code, sign up for SendGrid’s service, and start (to borrow a phrase) doing more faster!

We really appreciate Dave’s work on this project – this is a perfect example of what makes our community so strong.

Do you have a SendGrid story you’d like to tell? Give us a shout on Twitter, Facebook, email or phone, and we’ll discuss putting your story right here on ye ol’ bloggity for the rest of the community to enjoy.

Happy coding!

Tags: , , , ,


Director, Developer Relations at @SendGrid. Passionate about bringing people together around things they love. I tweet at @TimFalls.

2 thoughts on “Guest post: SendGrid takes the Cake[PHP] when it comes to SMTP

  1. Does this work with 2.0+?
    When i add sendgridemail to my components array it throws and error saying theres no such component

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>