Friday, 27 March 2009

UPDATED: Using SSMTP to send mail via GMail

UPDATED July 2014, to reflect the fact that google smtp servers are on port 587 now.

Often you will have a bash script that requires the ability to send emails out, such as alerts and status updates. Or perhaps you just want to get the normal alerts that all Unix servers attempt to send from time to time.

Out of the box Linux systems don't send email unless they are configured to do so. You can muck about configuring sendmail to use a "smarthost" if you like or you can do what I do and use a simple little smtp service that is quick and easy to configure to send mails via a GMail account.

Note:
If you have your own domain then it is probably better to use sendmail to send mails direct rather than relaying mail via the Big G

Obviously, for this all to work you will need a GMail account of your own. Is GMail still invite only? I have no idea. If it is and you need an invite then enter a comment below with your email address and I will be happy to send you one!

OK, let's get started.

First we need to remove sendmail and install ssmtp

sudo apt-get remove sendmail
sudo apt-get install ssmtp mailutils


SSMTP requires a little configuring so edit /etc/ssmtp/ssmtp.conf;

sudo vi /etc/ssmtp/ssmtp.conf

Enter the details for the following fields;

mailhub = smtp.gmail.com:587
rewritedomain = tuxnetworks.com
AuthUser=myusername@gmail.com
AuthPass=mypassword
UseSTARTTLS=YES
UseTLS=YES


Note:
You should replace "tuxnetworks.com" with your own domain as well as provide the details for your GMail account. Using 'myusername' and 'mypassword' is a recipe for FAIL

Testing to see if things work.

Send an email from the command line like this;

mail -s "test config" myusername@gmail.com

To see if it was sent you can check /var/log/mail.log;

tail -f /var/log/mail.log

You should see your email logged as "SENT" in the output there.

Here is a sample ssmtp.conf for your convenience;
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster

AuthUser=myusername@gmail.com
AuthPass=mypassword
UseSTARTTLS=YES
UseTLS=YES

# place where the mail goes. The actual machine name is required no 
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com

# Where will the mail seem to come from?
rewriteDomain=tuxnetworks.com

# The full hostname
hostname=myserver.tuxnetworks.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=yes


And that's it! Simples!

[ Tested and confirmed on Lucid and Natty servers ]

1 comment:

Helen Hunt said...

Thanks for this tip - just what I needed for my self-hosted web site that I'm currently running.

Nice tip :)