6

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

1 Answer 1

21

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

root=your_account@gmail.com
mailhub=smtp.gmail.com:587

FromLineOverride=YES
AuthUser=your_account@gmail.com
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: your_account@gmail.com
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 :)

4
  • You should be submitting this to Code Review - you've been submitting answers posing as questions
    – dbmitch
    Jul 16, 2016 at 3:57
  • Using the printf form of the command line with double quotes (as shown) results in the error: -bash: !\n: event not found Use single quotes around the whole line (between printf and | ) instead, and it works.
    – tim11g
    Sep 27, 2017 at 20:15
  • 1
    This method of setting up your Gmail account is now superceded by the App Passwords process as described here: support.google.com/accounts/answer/185833
    – Martin KS
    Dec 24, 2017 at 21:55
  • When I try to send the email the command doesn't do anything and doesn't give any errors, I have to kill it with ctrl + z . any ideas what's wrong?
    – Mike
    Apr 1, 2018 at 12:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.