Last active
April 22, 2025 15:40
-
-
Save velizarn/0c5c8bf19caaa316b2c0f4a0057178d0 to your computer and use it in GitHub Desktop.
Send email from bash script by using SendGrid API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Anyone found a quick way to add CC or additional To recipients?
https://gist.github.com/amithgc/fe5f1e4821e4a9809117513eb92a362a
What about files?
This doesn't work:
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
@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.
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}'"}]}'
yuck.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/amithgc/fe5f1e4821e4a9809117513eb92a362a