How to send email through sendgrid API using curl
Do you use sendgrid to send emails? if yes this article will help you to use curl to send emails through shell, lets see how!
Do you use sendgrid to send emails? if yes this article will help you to use curl to send emails through shell, lets see how!
What is sendgrid?
Sendgrid is an SMTP service provider, it provides SMTP servers to send email in batch using not only with the traditional way of reaching the SMTP port of the server but using an API as well. Using an API to sent emails has many benefits
- the benefit of using http ports and not SMTP ports that might be blocked due to firewall restrictions.
- Easy to integrate within your projects since it uses an HTTP API.
- Use an API key and not username / password.
What is curl?
curl is a command line tool for Linux, Windows and MacOS which enables to exchange data between a client and a server which runs a form of HTTP service like sendgrid. The benefit of curl is that can be used withing shell scripts that are easy to create and can automate manual labor
How to use curl to send emails with the sendgrid API
To send email through the sendgrid API we need first to generate an API key which will used instead of username and password, more info on this topic here: Manage SendGrid API Keys | Twilio
Create the following script and save it as sendgrid_sender.sh
#!/bin/bash
TO="email@example.com"
FROM="fromemail@example.com"
BODY="This is a test body"
SUBJECT="This is a test subject"
SENDGRID_API_KEY="xxxxxxxxxxxxxx"
curl --request POST --url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer "$SENDGRID_API_KEY \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email":"'"$TO"'"}]}],"from": {"email": "'"$FROM"'"},"subject": "'"$SUBJECT"'","content": [{"type": "text/plain", "value": "'"$BODY"'"}]}'Parameter explanation
- — request: This performs a POST request to the url of the sendgrid API
- — header Authorization: This header defines the sendgrid api key which needed for authorization
- $TO: The email recipient
- $FROM: The email of the sender
- $SUBJECT: The email subject
- $BODY: The email body
Finally you need to mark the script as executable
chmod +x sendgrid_sender.shTo run the script
./sendgrid_sender.shIf no error from curl command occurred on screen you should see on your mailbox the received email.
For more examples you can find more info here cURL Examples for Common Use Cases | Twilio (sendgrid.com)
Conclusion
Using the sendgrid API using curl can bring the benefits and the power of using the API to non developer people like sysadmins and devops who dont want to use a programming language like Java or C# to use a modern and super flexible tool like sendgrid.