Sending email with the lightweight smtp client msmtp from console or bash scripts

Sometime you want to send mail from console, e.g. bash scripts without installing a fully featured mail server locally. A lightweight smtp client that fullfills this requirement is msmtp. It is capable of connecting to upstream mail server via smtp, support encrypted connection (TLS) and can easily be used with its command line interface. Install it on debian based system with:

apt-get install msmtp
The configuration is either done system wide in /etc/msmtprc or in ~/.msmtprc in your home directory. Because the password is stored within, it is a good idea to restrict read access to that file. There are plenty of tutorial on the web that use gpg for password encryption, but then you have to provide that password during sending of email and cannot use it unattended e.g. in shell scripts.

Here is an example configuration:

# Set default values for all following accounts.
defaults
port 25
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Account specific information
account example
host <server name>
from <sender email address>
auth on
user <user name for smtp server>
password <password for smtp server>

# Set the default account
account default : example

Sending of mail involves calling

msmtp <receiver email address>

and entering the content. The mail is send by pressing <ctrl+d> which emits the end of file (EOF) signal. In order to set the subject, just enter

Subject: <subject>
as first line. All of this can be done from a shell script as well:
#/bin/bash
echo `cat <<EOF
Subject: TestTest
This is a test
EOF` | msmtp <receiver email address>