Sending Email using Sendgrid API

sendgrid1

One of the important features while creating server side code for some website/ web application is sending emails. But how do we send emails. There are different ways and packages using which you can setup SMTP ports and send emails. So why specifically sendgrid? Because along with SMTP relay, sendgrid also allows you to send emails using its Web API which makes work much easier. Here, we will discuss about using Web API.

SendGrid’s Web API sends mail via HTTP. Your server sends a message to SendGrid, and receives either a 250 message, indicating that the message was accepted by the receiving server, or a 400 or 500 message, indicating that something is wrong, prohibiting us from processing the request.

When everything is packaged correctly, SendGrid can process the request and then send it to the intended recipient’s ISP that responds with either a 250 message or a 500 message of their own, informing SendGrid whether or not the message was received. This process is more similar to putting your package in the mailbox and letting the post office review its information and deliver it for you.

Some sample requests:

Authentication:

 curl -X “GET” “https://api.sendgrid.com/v3/templates” -H “Authorization: Bearer Your.API.Key-HERE” -H “Content-Type: application/json”

Requests:

POST https://api.sendgrid.com/v3/templates/ HTTP/1.1
Content-Type: application/json

{
“name”: “new template name”
}

Responses:

HTTP/1.1 200 OK
Content-Type: application/json

{
“foo”: “bar”,
}

Errors:

You can go through the various errors from this link: https://sendgrid.com/docs/API_Reference/Web_API_v3/How_To_Use_The_Web_API_v3/errors.html

 

An example request for email is:

Request:-

POST https://api.sendgrid.com/v3/mail/send HTTP/1.1

Request body:-

{
“personalizations”: [
{
“to”: [
{
“email”: “[email protected]
}
],
“subject”: “Hello, World!”
}
],
“from”: {
“email”: “[email protected]
},
“content”: [
{
“type”: “text”,
“value”: “Hello, World!”
}
]
}

Response:-

{
HTTP/1.1 202
}

Published by

saptaks

Full Stack Developer, Open Source enthusiast