Tuesday, September 17, 2019

Using SSMTP to Send Email From Linux VPS Command Line Through Gmail Account

Ssmtp (Simple SMTP) is a little nice tool you can use under Linux command line to send out email. SSMTP allows users to transfer emails through an SMTP server from the Linux command line. It provides the means to connect to a mailhub with a proper configuration file. If your config file was set up right, all your worries regarding command line email sending can disappear.

System Repository Update
Before we do anything else we should bring the Ubuntu Repository up to date. Type the following command to update Ubuntu System Repository:
sudo apt-get update

Install the ssmtp package:
sudo apt-get install ssmtp

Configure the SSMTP config file.
sudo vi /etc/ssmtp/ssmtp.conf

You can just remove all contents in the original file and just add the following in.

[email protected]
[email protected]
[email protected]#

Optional configuration
Adding reverse aliases
A reverse alias changes the "From" address. This means you can make the email appear as if it's from a different email address. I personally haven't done this but if it's something you'd like to do then edit the revaliases file as follows:
sudo vim /etc/ssmtp/revaliases
Then add a new line similar to this:
root:[email protected]:smtp.gmail.com:587

Test sSMTP 
Once you've configurd sSMTP it's time to try and send an email. The simplest way to do this is to run sSMTP in a terminal with a recipient email address. So:

sSMTP will then wait for you to type your message, which needs to be formatted like this:

To: [email protected]From: [email protected]Subject: test emailHello World!

[email protected]:~$ ssmtp [email protected]
hello test

(Ctrl+D to end the edit content)

[email protected]:~$ ls
Mailx.sh  dead.letter  email.txt
[email protected]:~$ more email.txt
From: [email protected]
Subject: test email
Hello World!
[email protected]:~$
ssmtp [email protected] < email.txt [email protected]:~$ [email protected]:~$ cat email.txt Subject: Sending email using ssmtp Testing email body [email protected]:~$

Notes: Google Account Requirement

1. If you are getting authentication error:
  • Open your Google Account.
  • In the "Security" section, select 2-Step Verification. You might need to sign in.
  • Select Turn off.
  • A pop-up window will appear to confirm that you want to turn off 2-Step Verification. Select Turn off.
  • Allow less secure apps: If you don't use 2-Step Verification, you might need to allow less secure apps to access your account.  (Go to https://www.google.com/settings/security/lesssecureapps and Turn On this feature)

2. If you are getting authorization error
    • Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions. (Go to https://accounts.google.com/DisplayUnlockCaptcha and click Continue.)
    • Try signing in again from the blocked app

No comments:

Post a Comment