Send authenticated gmail from command line

Overview

You can send basic email from the command line. That’s been done a million times before, including by me!
Did you know that you can send email from the command line, from your gmail account that you authenticated to? That’s a big deal for some people. This document describes how to do that.

Sending gmail from command line

Install packages msmtp and mutt.
yum install msmtp mutt
Write the conf file and fill in the pertinent information.
# write conf file
tf=/etc/msmtprc
touch "${tf}"; chmod 0600 "${tf}"; chown root:root "${tf}";
cat <<EOF >"${tf}"
account default
tls on
tls_certcheck off
auth on
host smtp.gmail.com
port 587
user bgstack15@gmail.com
from bgstack15@gmail.com
password plaintextpassword
#
account second
tls on
tls_certcheck off
auth on
host smtp.gmail.com
port 587
user secondaccount@gmail.com
from secondaccount@gmail.com
password plaintextpassword
EOF

Now you can send an email with this command.
echo -e "From: Pretty Name\r\nSubject: Example subject\r\nContent goes here." | msmtp --debug --from=default -t destination@example.com

Sending attachments

Configure mutt if you want to send attachments from the command line.
cat <<EOF >> /etc/Muttrc.local
set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="Pretty Name"
set from=bgstack15@gmail.com
set envelope_from=yes
EOF

Send an email in html format and with an attachment.
subject="This is the subject
Mime-Version: 1.0
Content-Type: text/html"
mutt -a ~/attachment.txt -s "${subject}" -- destination@example.com << EOF
<html><body><pre>
This will be fixed width font. I find it useful for sending code fragments or log files.
</pre></body></html>
EOF

Authenticating to gmail from command line

The Arch Linux wiki provides an important reminder:

Tip: If using Gmail you’ll need to either

  • Allow “Less Secure Apps” in Settings > Security. Make sure to sign out of your other Gmail accounts first because the security settings part of Google Accounts can not manage concurrent sessions of more than one account.
  • Enable two factor authentication and create an app password.

References

  1. Send.sh from bgscripts package https://github.com/bgstack15/bgscripts/blob/master/usr/share/bgscripts/send.sh
  2. https://wiki.archlinux.org/index.php/Msmtp#Test_functionality
Advertisements

One thought on “Send authenticated gmail from command line

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s