Skip to content

Instantly share code, notes, and snippets.

@velizarn
Last active March 12, 2024 13:13
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save velizarn/0c5c8bf19caaa316b2c0f4a0057178d0 to your computer and use it in GitHub Desktop.
Save velizarn/0c5c8bf19caaa316b2c0f4a0057178d0 to your computer and use it in GitHub Desktop.
Send email from bash script by using SendGrid API
#!/bin/bash
SENDGRID_API_KEY=""
EMAIL_TO=""
FROM_EMAIL=""
FROM_NAME=""
SUBJECT=""
bodyHTML="<p>Email body goes here</p>"
maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'",
"name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": "'${bodyHTML}'"}]}'
curl --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer '$SENDGRID_API_KEY \
--header 'Content-Type: application/json' \
--data "'$maildata'"
# Voila! Sending emails from bash script is pretty simple
#
# https://sendgrid.com/docs/API_Reference/Web_API/mail.html
# http://stackoverflow.com/questions/17029902/using-curl-post-with-variables-defined-in-bash-script-functions
# http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-a-bash-variable
# http://stackoverflow.com/questions/25217462/concatenate-output-of-sed-to-bash-script-variable
# http://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script
# http://stackoverflow.com/questions/22043088/how-to-get-yesterday-and-day-before-yesterday-in-linux
# http://unix.stackexchange.com/questions/157747/force-rsyslogd-to-create-new-file-before-somebody-will-write-to-it
@pothi
Copy link

pothi commented Dec 13, 2022

@TitanRob16 Had the same issue. For me, I had to remove the single quote in the line --data "'$maildata'". I am on bash 5.0.x, btw.

@rad4alex
Copy link

Hey guys. How we can put value from bash variable as a body letter template. Can somebody help with it

Something like this :
bodyHTML=echo -e "$LETTER"

....

maildata='{"personalizations": [{"to": [{"email": "'${EMAIL_TO}'"}]}],"from": {"email": "'${FROM_EMAIL}'",
"name": "'${FROM_NAME}'"},"subject": "'${SUBJECT}'","content": [{"type": "text/html", "value": "'${bodyHTML}'"}]}'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment