How to send email from Ubuntu command line – using Gmail

This short guide will allow you to have your NAS send out email notifications with one command on the command line. You can then integrate this into various scripts etc to notify you when events happen (e.g. back script completes). To do this you’ll need a Gmail account (use an existing one or make a new one specifically for the NAS) to send the notification emails.

First install dependencies and open ssmtp.conf to edit:

apt-get -y install ssmtp mutt
nano /etc/ssmtp/ssmtp.conf

Comment out original lines and add this to bottom – replacing the relevant lines with your own details. Note that the ‘AuthPass’ line should be completed using the “application specific passwords” which Google lets you create ( ).

root=[your email address]
hostname=[your email address]
AuthUser=[your email address]
AuthPass=[app specific password]

Send a test email using the sendmail command. What we did above effectively replaced the sendmail application with ssmtp. Now when you run sendmail it will point to the ssmtp command instead.

printf "Subject: Test email" | sendmail -vf

You can keep using sendmail/ssmtp but mutt is actually much more usable and convenient so lets install that. It allows easier sending of emails from the command line with more use friendly options and easier switches for attaching files etc. We already installed it above so let’s configure its use.
I usually turn off the function which saves your sent mail locally as this can, over time, fill up your disk. Let’s also change the ‘from’ address for sent mail, nano /etc/.muttrc add this to the to:

set copy = no

Let’s test our email sending command now. First, let’s make a test file for email body contents:

mkdir ~/testemail/
echo "this is the body of the email">~/testemail/emailbody.txt

Make a file to test sending attachments:

echo “testcontents” > ~/testemail/attach.txt

Send a test email – no attachment:

mutt -s "Test Email" RECIPIENT.EMAIL.ADDESS < ~/testemail/emailbody.txt

Send test email with attachment:

mutt -s "Test Email" -a ~/testemail/attach.txt -- RECIPIENT.EMAIL.ADDESS < ~/testemail/emailbody.txt


Useful sources

Leave a Reply

(email optional)

Warning: Undefined array key "rerror" in /home/public/blog/wp-content/plugins/wp-recaptcha/recaptcha.php on line 291