Send Email with HTTP API – curl, ctrl-X E and Sendgrid API

Use interactive console and HTTP requests to access APIs. Here is an example of automatic mail sending with SendGrid and curl.
Use SendGrid API documentation for curl examples. Before you start coding, develop your code in interactive console. When you type a command and get immediate answer, the feedback loop is short. Bash and iPython are good choices.
In Linux command line bash, press ctrl-X E to edit command line in nano. Save with ctrl-X y enter. Use your own API key. Put it all on one line, it’s split here for readability. This example request is a literal quote from SendGrid curl documentation.

curl --request POST  --url
--header 'Authorization: Bearer YOUR_API_KEY'
--header 'Content-Type: application/json'
 --data '{"personalizations":
[{"to":[{"email": ""}]}],
"from": {"email": ""},
"subject": "Hello, World!","content":
[{"type": "text/plain", "value": "Heya!"}]}'

When you run it, you get a response from SendGrid API.

{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked","field":null,"help":null}]}

Indeed, you need to register for an API key to actually send email. You should probably create new API key from SendGrid web interface to know the API key string. Sendgrid API keys also have a long reference number that is not the working API key – so the number you see prominently in SendGrid user interface is not the correct API key used in the request.
After you get it working, you can easily use any HTTP API with Python requests library. No need to install, update and learn a quazillion different libraries for each web API.
Updated: fixed code styling.

Posted in Uncategorized | Tagged , , , , | Comments Off on Send Email with HTTP API – curl, ctrl-X E and Sendgrid API

Comments are closed.