Igor's Blog
Programming, DIY, Games, Hacks, and Tech

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.

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.

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.

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!

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...
"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).
function sendEmail($to, $subject, $message, $sendgrid_api_key) {
$mail = new \SendGrid\Mail(
new \SendGrid\Email('Sender', 'sender@example.com'), /* from */
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).

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

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.


Please leave your comments or feedback below!
comments powered by Disqus
Other posts you may like...

Recent Blog Posts

How to enable the full stack trace in Maven's Surefire plugin for JUnit testing

Twelve elements of the Burst Mining Pool interface explained

TPG FTTB settings for the Billion BiPAC 8700AXL 1600 modem router

Protecting old Atari Lynx game boxes with snug fit plastic sleeves

How to fix SoapUI javax.net.ssl.SSLHandshakeException calling WebLogic 12.2 web services on Java 8

Woolworths (WOW) shares disappeared from Computer Share Investor Centre

Connecting the Dell UltraSharp U3415W monitor to a MacBookPro via USB-C

How to add/change PHP versions appearing in MAMP preferences

Fix the ORA-00904: ORA_ROWSCN: invalid identifier error in SQLDeveloper with a few easy steps

G Suite Gmail is broken on Safari due to new Google Content Security Policy settings

Recent Galleries

Protecting old Atari Lynx game boxes with snug fit plastic sleeves

Monument Valley 2 is released and does not disappoint

Space Food - Chocolate Ice Cream with Chocolate Chips

Legeod Star Wars AT-DP kit

DIY spare parts computer build with a RAIDMAX Anura case

Fake 'Lepin' brand Lego packaging

Hardwood garden bench with clear resin void filler

Fixing a 3D printer extruder that stopped heating up

Easily increase disk space in a Lenovo Ideapad 100S 14" laptop with an M.2 SSD

Making a multi-piece 3D printed solder spool holder stand

My Other Web Sites

Igor and Elise's Travels
Riverside Expressway Cam
300 George St Blogumentary

My Online Tools

UUID to OID Converter
Guru JSON-RPC Tester
Extrudifier Object Designer
Travel ┬ÁBlog

Blogs and Friends

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity
Don't forget to
my Facebook page for more great articles!
Don't show this again