Rails and Emails

Having just installed our Rails server on Heroku, we were looking for a way to send out emails to confirm email addresses. The line of least resistance seemed to be Gmail; everyone loves Gmail and there were quite a few articles on the subject. So we set it up and it worked… for a while.

It seems that Google have increased the security of the mail system and the option to use less secure apps no longer allows our Rails server to send emails. Instead Gmail warns that an unknown device in Virginia (i.e. a Heroku server) is trying to send email using the account and has been blocked. Even saying that the device belongs to me (which it does… kind of) didn’t improve matters. A different approach was required.

Rails had been configured to use SMTP to send email via Gmail so it made sense to adopt another email service that supported the same approach. Mailgun is offered by Heroku and seemed to fit the bill.

As soon as it’s installed using Heroku, a bunch of Mailgun environment variables are setup and a “Sandbox” email domain is created to get you up and running. The Gmail configuration  was replaced by this:

config.action_mailer.smtp_settings = {
 :address => ENV['MAILGUN_SMTP_SERVER'],
 :user_name => ENV['MAILGUN_SMTP_LOGIN'],
 :domain => 'yourdomain.heroku,com',
 :authentication => :plain

To get this to work you have to specify authorised recipients (i.e. email addresses) via the Mailgun console (which is accessed via the Heroku Overview page). Up to five authorised recipients are allowed which is enough to demonstrate that everything is setup okay but nothing more. To get it working fully, you have to have your own domain.

Mailgun suggest that you set up a subdomain for sending emails but you can use Mailgun to forward incoming emails to mailboxes of your choice (Mailgun does not offer IMAP or POP3 access) as well as to send outgoing emails so it may be easier for you to use the top-level domain. It certainly looks that way to me.

Once you have entered your email domain in the Mailgun console you can see the settings it needs to be entered on your DNS server. Once the DNS settings have propagated, you  take the username and password that Mailgun has created for your new email domain and update the environment variables MAILGUN_SMTP_LOGIN and MAILGUN_SMTP_PASSWORD. Then everything should work.

Having done this, I’m not sure why I contemplated using Gmail in the first place. You live and learn.

Leave a Reply

Your email address will not be published. Required fields are marked *