SSMTP Relay & Mail Delivery in Rails

Role separation and vertical scaling between the database and the app servers is almost taken for granted, but is no reason that we can't do this for mail delivery as well! Following up on some of the comments from my earlier post on sendmail, configuring and maintaining a secure, high-performance mail server is a non-trivial task. Hence, we should be able to do it once, and then tell Rails to use that server for all mail related tasks - thankfully, the process is easy.

Painless mail MTA: SSMTP

Assuming you already have Postfix/Exim/Sendmail configured on one of your machines (dedicated mail server), we're good to go. In fact, a great benefit of this approach is the fact that the SMTP server does not have to be local - it can be a service like GMail, or your own server located on a different network. To make things click, we'll install SSMTP on all of our app servers:

SSMTP - A secure, effective and simple way of getting mail off a system to your mail hub. It contains no suid-binaries or other dangerous things - no mail spool to poke around in, and no daemons running in the background. Mail is simply forwarded to the configured mailhost.

Use your favorite installer (apt, yum, etc.) to get ssmtp setup on your system. If you have sendmail installed, it will prompt you to remove it as part of the process - from now on, all applications relying on sendmail will interact with ssmtp.

Configuring GMail as external SMTP

Configuring ssmtp can't get any easier. Navigate to /etc/ssmtp and open up ssmtp.conf. Below is a fully featured, sample configuration file for relaying all of your mail to GMail servers:

# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster

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

# GMAIL configuration
mailhub=smtp.gmail.com:587
AuthUser=youremail@gmail.com
AuthPass=pass
UseSTARTTLS=YES

# The full hostname
hostname=machinehostname

# 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

Next, open up your environment.rb, set ActionMailer to use sendmail, and we're all done:

ActionMailer::Base.delivery_method = :sendmail

That's it, from now on your Rails application will think it is using sendmail, not realizing that ssmtp is quietly doing all the work of interacting with Google's servers. In similar fashion, you can point your app servers to use a dedicated mail-server machine inside or outside of your network by changing your ssmtp.conf!


Ilya Grigorik

Ilya Grigorik is a web performance engineer and developer advocate at Google, where his focus is on making the web fast and driving adoption of performance best practices at Google and beyond.