Problem
You would like to be able to automatically send some emails (ie reports) from a linux server, using a bash script that runs in cronjob, without installing an email server on the linux server.
Solution
here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#!/bin/bash # Email setup SENDGRID_API_KEY="your_sendgrid_api_key" FILENAME_ATTACH="title_of_your_attachment" FILENAME_ZIP="the_path_to_your_zip_file" FILENAME_BASE64_TMP="the_path_to_temporary_base64_encoding" EMAIL_TO="email_to_address" EMAIL_SUBJECT="email_subject" EMAIL_FROM="email_from_address" EMAIL_MESSAGE="your_email_message" function email_exports() { FILENAME_BASE64=$(base64 -w0 $FILENAME_ZIP); REQUEST_DATA='{"personalizations": [{ "to": [{ "email": "'"$EMAIL_TO"'" }], "subject": "'"$EMAIL_SUBJECT"'" }], "from": { "email": "'"$EMAIL_FROM"'" }, "content": [{ "type": "text/plain", "value": "'"$EMAIL_MESSAGE"'" }], "attachments": [{ "content": "'"$FILENAME_BASE64"'", "filename": "'"$FILENAME_ATTACH"'" }] }'; # We need to store the base64 locally as the text # is too big for sending directly with curl echo $REQUEST_DATA > $FILENAME_BASE64_TMP curl -X "POST" "https://api.sendgrid.com/v3/mail/send" \ -H "Authorization: Bearer $SENDGRID_API_KEY" \ -H "Content-Type: application/json" \ -d "@$FILENAME_BASE64_TMP"; rm $FILENAME_BASE64_TMP } email_exports |