Send Emails From Gmail Through Shell/Script – Linux
Table of Contents [hide]
Intro ∞
Sometimes there is a need to send an email via command line, or in a script (such as using PHP’s mail()
method); but there is not an MTA (postfix, sendmail, etc) running on the machine. Note that while it is possible to set an MTA up as a gmail smarthost, they will be overkill for this simple scenario. The best program to use for this purpose is ssmtp
– it accepts a mails stream from standard input and forwards the message to a remote MTA for processing.
Install ssmtp ∞
- Install
ssmtp
using your distro’s package manager# Debian/Ubuntu sudo apt-get install ssmtp # CentOS/RedHat/Fedora sudo yum install ssmtp
- Disable sendmail (if enabled)
sudo service sendmail stop sudo chkconfig sendmail off mkdir /root/.sendmail_backup mv /usr/sbin/sendmail /root/.sendmail_backup
- (Optional) Symlink
ssmtp
in place of sendmailmv /usr/bin/sendmail /usr/bin/sendmail.orig ln -s /usr/local/ssmtp/sbin/ssmtp /usr/sbin/sendmail
Configure ssmtp ∞
- Edit
/etc/ssmtp/ssmtp.conf
, update the following settings:AuthUser=email@gmail.com AuthPass=Super_Secret_Password FromLineOverride=YES mailhub=smtp.gmail.com:587 UseSTARTTLS=YES
- Test
echo "Test email body" | mail -s "Test Subject" email@domain.com
Why do I have to disable sendmail while ising ssmtp? Why not use both?
Good call. For my usage, I was making this a drop-in replacement for sendmail in order to avoid changing a bunch of code. I added a bit about it being optional, thanks for pointing that out.