Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Last active May 15, 2019 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/4bb5e0ff3090f150c6696793cf8e8488 to your computer and use it in GitHub Desktop.
Save nfsarmento/4bb5e0ff3090f150c6696793cf8e8488 to your computer and use it in GitHub Desktop.
Sending emails using Gmail and msmtp on Ubuntu / Debian
#!/bin/sh
# Sending emails using Gmail and msmtp on ubuntu 18.04
# Author: [Nuno Sarmento](https://www.nuno-sarmento.com)
# Git: [Git](https://github.com/nfsarmento)
# Usage: chmod +x setup-msmtp-for-gmail.sh && ./setup-msmtp-for-gmail.sh
# You should enable "Less secure app access" under gmail/account/security.
sudo apt-get update -q
sudo apt-get install msmtp
sudo apt-get install msmtp-mta ca-certificates heirloom-mailx -yq
if command -v zenity >/dev/null; then
GMAIL_USER=$(zenity --entry --title="Gmail username" --text="Enter your gmail username with domain (username@gmail.com):")
GMAIL_PASS=$(zenity --entry --title="Gmail password" --text="Enter your gmail password:" --hide-text)
else
read -p "Gmail username with domain (username@gmail.com): " GMAIL_USER
read -p "Gmail password: " GMAIL_PASS
fi
echo # an empty line
if [ -z "$GMAIL_USER" ]; then echo "No gmail username given. Exiting."; exit -1; fi
if [ -z "$GMAIL_PASS" ]; then echo "No gmail password given. Exiting."; exit -1; fi
sudo tee /etc/msmtprc >/dev/null <<__EOF
# Accounts will inherit settings from this section
defaults
auth on
tls on
tls_certcheck off
# tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile /var/log/msmtp.log
# A first gmail address
account gmail
host smtp.gmail.com
port 587
from $GMAIL_USER
user $GMAIL_USER
password $GMAIL_PASS
# Set a default account
account default : gmail
__EOF
sudo chmod 600 /etc/msmtprc
sudo chown -R www-data:www-data /etc/msmtprc
HOST=$(hostname)
sudo mail -vs "Email relaying configured at ${HOST}" $GMAIL_USER <<__EOF
The postfix service has been configured at host '${HOST}'.
Thank you for using this postfix configuration script.
__EOF
echo "I have sent you a mail to $GMAIL_USER"
echo "This will confirm that the configuration is good."
echo "Please check your inbox at gmail."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment