Skip to content

Instantly share code, notes, and snippets.

@dr5hn
Last active September 19, 2023 09:19
Show Gist options
  • Select an option

  • Save dr5hn/bdb0168c73a9279e9f49ff1aab39f472 to your computer and use it in GitHub Desktop.

Select an option

Save dr5hn/bdb0168c73a9279e9f49ff1aab39f472 to your computer and use it in GitHub Desktop.
Send email from bash or shell script by using SendGrid API
#!/bin/bash
#-----------------------------
# REFERENCES
# https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
# https://sendgrid.com/docs/for-developers/sending-email/curl-examples/
# https://sendgrid.com/docs/API_Reference/Web_API_v3/How_To_Use_The_Web_API_v3/errors.html
#-----------------------------
SUBJECT="🗄️ Backup Reports";
SENDGRID_API_KEY=""
EMAIL_TO="[email protected]"
FROM_EMAIL="[email protected]"
FROM_NAME="Backup Server"
if [ ! -z "$SENDGRID_API_KEY" ] && [ "$SENDGRID_API_KEY" != "" ]; then
# Attachment needs to be base64 encoded
REPORTS=$(base64 reports.txt)
# Prepare the recipe
REQUEST_DATA='{
"personalizations": [{
"to": [{ "email": "'"$EMAIL_TO"'" }],
}],
"subject": "'"$SUBJECT"'",
"from": {
"email": "'"$FROM_EMAIL"'",
"name": "'"$FROM_NAME"'"
},
"content": [{
"type": "text/html",
"value": "Team, <br><br> Here are the logs🗒 of backup script for today, Hope everything is okay and you have a nice day 🎉😁<br><br>Regards,<br>Backup Bot🤖"
}],
"attachments": [{
"content": "'"$REPORTS"'",
"type": "text/plain",
"filename": "reports.txt"
}]
}';
# Shoot the email
curl -X "POST" "https://api.sendgrid.com/v3/mail/send" \
-H "Authorization: Bearer $SENDGRID_API_KEY" \
-H "Content-Type: application/json" \
-d "$REQUEST_DATA"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment