Raspberry PI - Send mail from command line using GMAIL smtp server

mikia picture mikia · Jul 15, 2016 · Viewed 22.8k times · Source

How can I send email from Raspberry Pi using my gmail account?

I would like to send mail from command line and use this method in my scripts.

Envirenment:

Hardware: Raspberry PI 3
OS: Jessie
SMTP: smtp.gmail.com

Answer

mikia picture mikia · Jul 15, 2016

I use this method on my Raspberry Pi 3 devices:

Google account setting

  1. Login to your gmail account
  2. Go to: Settings -> Accounts and Import -> Other Google Account settings
  3. Go to: Personal info & privacy -> Account overview
  4. Go to: Sign-in & security -> Connect apps & sites
  5. Set option Allow less secure apps to ON

Install SSMTP
sudo apt-get install ssmtp

Save original conf file
sudo mv /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.bak

Create new conf file (with vi, or some other text editor)
sudo vi /etc/ssmtp/ssmtp.conf

file content

[email protected]
mailhub=smtp.gmail.com:587

FromLineOverride=YES
[email protected]
AuthPass=your_password
UseSTARTTLS=YES
UseTLS=YES

# Debug=Yes

Secure conf file

sudo groupadd ssmtp
sudo chown :ssmtp /etc/ssmtp/ssmtp.conf

If you have error on this step like ''cannot access'' ... you must find ssmtp file and use that path: sudo find / -name "ssmtp"

sudo chown :ssmtp /usr/sbin/ssmtp
sudo chmod 640 /etc/ssmtp/ssmtp.conf
sudo chmod g+s /usr/sbin/ssmtp

Sending mail from (only one) command line

echo "This is a test" | ssmtp recipient.address@some_domain.com

or

printf "To: recipient.address@some_domain.com\nFrom: RaspberryPi3\nSubject: Testing send mail from Raspberry\n\nThis is test. Best Regards!\n" | ssmtp -t

Sending mail from file test.txt
Make file with similar content:

To: recipient.address@some_domain.com
From: [email protected]
Subject: Testing send mail from Raspberry

This is test mail (body)

Best Regards!

Now you can send mail from file

ssmtp recipient.address@some_domain.com < test.txt

That's all :)