Send Email on Raspberry Pi from Command Line with Msmtp

Msmtp is an SMTP client it itransmits a mail to an SMTP server (for example at a free mail provider) which takes care of further delivery.

To use this program with your mail user agent (MUA), create a configuration file with your mail account(s) and tell your MUA to call msmtp instead of /usr/sbin/sendmail. With Msmtp on Raspberry Pi you can use command to send email from Raspberry Pi or use some script to send an email automatically

Install Msmtp

In order for the Raspberry Pi to send email from command line you need to install packages on the Raspberry. You are going to need the following packages
  • msmtp msmtp is an SMTP client that can be used to send mails from Mutt and probably other MUAs (mail user agents). It forwards mails to an SMTP server (for example at a free mail provider), which takes care of the final delivery. Using profiles, it can be easily configured to use different SMTP servers with different configurations, which makes it ideal for mobile clients.
  • ca-certificates This package includes PEM files of CA certificates to allow SSL-based applications to check for the authenticity of SSL connections.
To install the msmtp and ca-certificates packages run following command:
sudo apt-get update
sudo apt-get install msmtp ca-certificates
If there are no error at installation you can continue to next step

Configure Msmtp

To configure the msmtp, you need create msmtp configuration first on /etc folder and edit the msmtprc file using nano or your favorite text editor
cd /etc
sudo touch msmtprc
sudo nano msmtprc
After you've on nano edit's interface you can add this configuration file and save the configuration
account default
host smtp.gmail.com
port 587
logfile /tmp/msmtp.log
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

auth login
user [email protected]
password thepassword
from First Last Name

account account2

Testing

To test if msmtp working properly, run following command:
echo -e "Subject: Test Mail\r\n\r\nThis is a test mail" |msmtp --debug --from=default -t [email protected]
Explanation
  •  Subject: is the subject of the mail and after \r\n\r\n is the mail's main messages
  • –debug is the output log of the sending mail
  • –from=default is which account used for sending the mail
  • -t username[at]gmail.com  is the destination address
Then check the destination email Inbox

References

  1. Installing and Configuring mSMTP
  2. Images by Cairo on Flickr, used under CC BY 2.0 / Added more shadow from original

Comments