Automatic emails using bash and sendgrid


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.


  • Create an account in Sendgrid and follow the directions for using WebAPI with curl
  • 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.
  • Add your script to crontab
  • Changing default editor for crontab from nano to vim


    You would like to change the default editor for crontab from nano to vim.


    Add the following to the ~/.selected_editor:

    or run the select-editor and choose vim-basic (4)

    Running script/runner in production environment

    Following from a previous post about email scheduling with runner and cron, it turns out that the runner default behaviour is to run in the development environment.

    Although by reading the help for the script/runner, there is a suggestion to run it with the -e production added to the end, it doesn’t seem to be working.

    The solution to make it running in the production environment was to delete the first line (shebang) from step 3 on this post

    and then use the following in the cron setup:

    Have a look on paragraph Alternative Usage here

    Ruby on Rails email scheduling using runner and cron

    You want to send emails from a Ruby on Rails application, when there is a specific condition on a database table. If the database table gets modified by another application outside Rails you cannot use an observer model.

    We already assume that:

    • You are using a database
    • You have a model named voicemail (id, number_id, audio, created_at, updated_at)
    • You have a model named number (id, voicemail_email_set, voicemail_email, ….)
    • A mail server to use (smtp in our case)
    • Another application (voice application) populates the voicemail table but with empty updated_at values

    So the steps we have to follow are:

    1. Change the settings in your config/environment.rb file to use the settings for your mail server, and make sure you restart your application after the changes:
    2. Create your mailer model (ie voicemail_mailer.rb), in app/models:
    3. Create your email scheduler in file lib/email_scheduler.rb: