Automatic emails using bash and sendgrid

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

  • Create an account in Sendgrid and follow the directions for using WebAPI with curl
    here
  • Set up your bash script to use the API key and have a script like the following. If you want to use big or multiple files you will need to use a temporary file for the base64 encoding, as in the example below, as there is a limit in curl.
    #!/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
  • Add your script to crontab