how to set up sending mail from the command line

Linux
Networking
Author

Vinh Nguyen

Published

July 10, 2010

Often times I want to send emails to myself when a job is done or when something happens on the computer/server. Using the command line is the most portable and obvious as most software I run (eg, R) can execute from it.

This site shows how to use mail and mutt to send emails from the command line, but does not show how to set things up. Setting up actually took me a long time to figure out, as I wasn't familiar with Mail User Agent (MUA), Mail Transfer Agent (MTA), etc. This site can help clear things up regarding those issue.

Now, down to business. We'll need to install some software:

sudo apt-get install mutt msmtp bsd-mailx ## mailutils

mailutils contain the mail command, which allows one to send mail but not attach files. mutt is an MUA that allows one to send mail from the command line and attach files. msmtp is an MTA that we can use with mail and mutt (mutt v1.5.x and above has it's own built in smtp capabilities).

~/.msmtprc:

account default
host smtp.gmail.com
port 587
from my.email.address
tls on
#tls_starttls on
tls_trust_file /usr/share/ca-certificates/mozilla/Equifax_Secure_CA.crt
auth on
user my.username (email address for gmail)
password my.password
logfile ~/.msmtp.log

Need to execute chmod 600 .msmtprc (user read/write only )or it won't work.

~/.mailrc:

set sendmail="/usr/bin/msmtp"

~/.muttrc:

## following if want to use msmtp to send mail
set sendmail = "/usr/bin/msmtp"
##
set realname = "vqn laptop"
set from = my.email.address
set use_from=yes
set envelope_from=yes
## uncomment following and comment above sendmail line if want to use
## mutt's built-in smtp
##set smtp_url="smtp://username@smtp.gmail.com:587"
##set smtp_pass="my.password"

chmod 600 .muttrc since it contains password.

Note that to use TLS with msmpt, you need to set the certificate file. On a debian-basd system, you can find it in the /usr/share/ca-certificates/ directory, which has many. See below for references.

This site shows how to set up mutt with msmtp. This site shows how to set things up, along with the certificate stuff. More on certificate here. This will tell more on how to use the built-in smtp of mutt. The wiki of course has more information.

UPDATE 8/24/2011: From this post, use mail from bsd-mailx instead of mailutils to have the mail command working instead of the error msmtp: no recipients found.

UPDATE 11/13/2011: If you want to be able to email as the root user, make sure these instructions are set up for the root user's home directory, /root/.