The following is a guest post from Alex Reed, one of SendGrid’s European Ambassadors.
I would be lying if I didn’t say that my favourite feature in the SendGrid API set is the Inbound Parse Webhook. Being able to receive email into a web application/service, as easily as SendGrid makes it, is an absolute joy! (It even allows the parsing of attachments, and email header-data!)
My background is C#, making apps to hack video games, and some Ruby doing web services. Gaming is a huge part of my background, which actually got me into programming in the first place. So it gives me great pleasure being able to combine the two in a sample SendGrid hack.
As you can see in the above Vine, we’ll be hacking Halo by sending an email.
Set Up the Parse Webhook
To receive an email in your application, you can use the Inbound Parse Webhook. Once the data is in our app, we can send it to the XBox. There’s a quick way and a slightly longer way, both detailed in this Parse Webhook tutorial:
The five minute approach, using SendGrid’s bymail.in service
The 48 hour approach, using your own domain name due to DNS propagation times (although it’s usually much shorter than this)
To route the email to our local computer, we use ngrok, which makes debugging easier. Ngrok forwards requests from an ngrok subdomain to a process running on your local machine. Martyn has a blog post detailing how to set up ngrok.
Receive Email into Your .NET MVC 5 Application
For this demo, I will be using c#. Bearing this in mind, the demo will be exactly the same whether in VB or c#. To convert any code snippets into VB, please use this website to convert the C# to VB.
c# MVC currently has an issue with a mime-type header received from SendGrid. To get around this, we need to write a custom attribute and apply it to the method that takes in our POST request in our application.
First, we’re going to need to create a model for the data sent to our web application. Here is a sample model containing the format of the POST request to get you started:
Now that we have that, we can add our attribute code:
Finally, all we have to do is apply the attribute to our method that receives POST requests. We also need to add the [ValidateInput(false)] attribute to the method to stop C# misbehaving.
The Email model with all our data will now be accessible within the method. To access that data, we need to look in the ActionContext Action Arguments like so:
If you send an email to, for example, email@example.com, it will now be received into the MVC application and held in the ‘email’ variable. Now we can use this to do awesome stuff such as, hacking video games, submitting expenses, or even adding Steve Buscemeye’s to Selfies!
I realise I haven’t included much about hacking video games themselves, but for the complete set of code (including parsing and sending commands from Email into Halo), check out my GitHub. It includes the complete solution with all dependencies and NuGet packages.