Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

After struggling with emails not being being delivered to subscribers using SMTP over at travelblog.ws I started to look at alternatives to sending email and came across SendGrid. With SendGrid it's possible make use of your existing code that sends emails while taking SMTP completely out of the picture, at least on your end.

The problem that I was having was that my host (GoDaddy) has a very poor MX reputation. Some email providers like Microsoft (live.com, hotmail.com, outlook.com) outright block any email coming from such hosts. Furthermore it is also not possible to use a 3rd party SMTP service on my host since any outbound SMTP connections are blocked. It's a catch-22 situation, you either stick with bad reputation and risk your emails not being delivered or...well there is no or, unless you use a service like SendGrid.

SendGrid solved both of my issues. First they have a good reputation so your emails will get delivered and second the service can be accessed in a RESTful manner so you're not connecting to any SMTP server. Best of all, you get the first 12k emails in the month for free, which for me was more than enough.

Over at travelblog.ws it took less than an hour to go from signing up to having a fully functional SendGrid based email subsystem in place. Lets see how I went about it.

I signed up for a Free 12k $0.00 account.
sendgrid2.png


After all the usual account verifications I created an API key. The admin console is very intuitive and easy to navigate, I was impressed already.
sendgrid3.png


Because I was going to use this API key for actual sending, I created a General key (under Settings > API Keys). When creating a new key, it's possible to limit what functionality it would have access to, I set it to Full Access for all the features I wanted and No Access for features that I was never going to use. I didn't bother with any Read Only settings.
sendgrid4.png




Once I clicked Save, my key was presented for a one-time viewing only. This was important so I took note of the key for future use!
sendgrid5.png


With the API key in hand it was time to write some code. I used Composer to download all the prerequisites, the relevant part of my composer.json file looked like...
 composer.json
{
...
"require": {
"sendgrid/sendgrid": "~5.0.9"
}
...
}


The majority of the work on my side was actually to do with storing the API key in my database rather than implementing SendGrid code. There were some very good examples of integration code online too, which I relied on. Below is what my SendGrid mailing code ended up looking like (I extracted it into a separate function for this post).
 PHP
function sendEmail($to, $subject, $message, $sendgrid_api_key) {
$mail = new \SendGrid\Mail(
new \SendGrid\Email('Sender', '[email protected]'), /* from */
$subject,
new \SendGrid\Email(null, strtolower($to)), /* to */
new \SendGrid\Content("text/html", $message) /* message */
);
$sg = new \SendGrid($sendgrid_api_key);
$response = $sg->client->mail()->send()->post($mail);
if ($response->statusCode() >= 200 && $response->statusCode() < 300) {
return true;
}
$errResp = json_decode($response->body(), true);
$err = $errResp['errors'][0]['message'];
error_log('Error: ' . $err);
return false;
}


The code is fairly straight forward but lets look at its main features. The very first thing I do is create a Mail object, this represents the email that I'm wanting to send. It has a sender (line 3), subject (line 4), the receiver (line 5) and the message being sent (line 6). The Email objects represent an email address each, these can have both a name and email address portions. For the message, I used a Content object and specified that it is text/html. My message does have HTML markup in it so that was necessary. If I didn't have HTML, the mime type would have been set to text/plain.

On line 9 I create the SendGrid object itself and pass the API key to it. Line 10 is where the mailing of my message happens. The rest of the code is to do with response processing, I won't go into its details.

There you are, it's pretty simple really, just a handful of lines of code to get up and running. Now back at the dashboard I could already see statistics based on my testing. It's quite neat and SendGrid even tracks whether your emails have been opened by the reader (via a tracking pixel).
sendgrid6.png


The Activity feed shows events that occurred e.g. message was processed, opened, delivered, etc. That can be useful for debugging purposes.
sendgrid7.png


There are many other features that SendGrid provides like user lists, categories, template based emails, etc. The list of features is quite extensive. I only used the mail sending feature and was really impressed with how easily and quickly I could integrate this API into my code. I'd like to explore SendGrid in the future to manage mailing lists, when I do I'll write another post describing my experience with how SendGrid fares.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.