Command Line Email – Send Mail with Image Attachment Using Gmail

emailgmailssmtp

Building on the previous post where the requirement was to have cron jobs send status messages via a single command line, as posted here:

Simplest way to send one-line mail out via command line using gmail?

The question came up as to how to use a single line to send an attachment file.

Scenario:

cron job generates the output file like so:

cd /home/pi/python
gnuplot plt12

the program file plt12 includes the following two lines:

set output "pl12.png"
set terminal png font "arial,11"

This is being done on a Rpi3B system connected via USB to a Nano for the ADC which does the data logging.

So, the question is, what is the easiest way to send that plot file image, using a single command line, via gmail?

Best Answer

With mutt:

SMTP_URL='smtps://user:password@smtp.gmail.com' mutt \
  -F /dev/null \
  -e 'set from="Me <user@gmail.com>"' \
  -e 'set smtp_url=$SMTP_URL' \
  -s 'pl12.png file' \
  -a pl12.png --  \
  someone@example.com << EOM
Hi,

see pl12.png attached.

-- 
Me
EOM

Like every shell code, you can always put it on one line if that takes your fancy, though that doesn't help with legibility:

printf 'Hi,\n\nsee pl12.png attached\n\n-- \nMe\n' | SMTP_URL='smtps://user:password@smtp.gmail.com' mutt -F /dev/null -e 'set from="Me <user@gmail.com>"' -e 'set smtp_url=$SMTP_URL' -s 'pl12.png file' -a pl12.png  -- someone@example.com
Related Question