Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 423
mikia Avatar asked Jul 15 '16 08:07

mikia


People also ask

How do I use Gmail SMTP server to send emails?

Set up the app or device with the Gmail SMTP serverOn your device or in the app, enter smtp.gmail.com as the server address. In the Port field, enter one of the following numbers: If you're using SSL, enter 465. If you're using TLS, enter 587.

Can you send email from command line?

sendmail Command Sendmail is one of the most popular SMTP servers in Linux. You can easily send emails directly from the command line using the sendmail command.

How use SMTP command in Linux?

SMTP DESTINATION SYNTAXLook up the address(es) of the specified host, and connect to the specified port (default: smtp). Connect to the host at the specified address, and connect to the specified port (default: smtp). An IPv6 address must be formatted as [ipv6:address].


1 Answers

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 :)

like image 116
mikia Avatar answered Oct 18 '22 05:10

mikia