How to send an email in a command line?

The approach below probably is not safe, since it exposes your email address with password.

1. Install ssmtp : sudo apt-get install ssmtp

2. Edit the ssmtp config file : sudo gedit /etc/ssmtp/ssmtp.conf
Enter this in the file:
root=username@gmail.com
mailhub=smtp.gmail.com:465
rewriteDomain=gmail.com
AuthUser=username
AuthPass=password
FromLineOverride=YES
UseTLS=YES

3. Enter the email address of the person who will receive your email:
ssmtp recepient_name@gmail.com
Now enter this:
To: recipient_name@gmail.com
From: username@gmail.com
Subject: Sent from a terminal!
Your content goes here. Lorem ipsum dolor sit amet, consectetur adipisicing.
(Notice the blank space between the subject and the body.)

To send the email: Ctrl + D

4. You can also save the text mentioned in Point 5 into a text file and send it using:
ssmtp recipient_name@gmail.com < filename.txt

5. Want to send with an attachment? You may use mpack.
sudo apt-get install mpack
mpack -s subject_title -d path_to_body picture.png email_address@example.com

(mpack -s “$EMAIL_SUBJECT” -d $EMAIL_BODY -c application/octet-stream $v_source $V_EMAIL)

6. Or, you could use “mail” to send an email out
sudo apt-get install mailutils

On the security issue…

Because your email password is stored as cleartext in /etc/ssmtp/ssmtp.conf, it is important to secure the file. Securing ssmtp.conf will ensure that:

  • if any users have unprivileged access to your system, they cannot read the file and see your email password, while still letting them send out email
  • if your user account is ever compromised, the hacker cannot read the ssmtp.conf file, and therefore your email password, unless he gains access to the root account as well

To secure ssmtp.conf, do this:

Create an ssmtp group:

# groupadd ssmtp

Set ssmtp.conf group owner to the new ssmtp group:

# chown :ssmtp /etc/ssmtp/ssmtp.conf

Set the group owner of the ssmtp binary to the new ssmtp group:

# chown :ssmtp /usr/bin/ssmtp

Make sure only root, and the ssmtp group can access ssmtp.conf:

# chmod 640 /etc/ssmtp/ssmtp.conf

Set the SGID bit on the ssmtp binary.

# chmod g+s /usr/bin/ssmtp

Now, all the regular users can still send email using the terminal, but none can read the ssmtp.conf file.

 

Advertisements