TWIL: Simple Rails Mail
Working with Rspec is awesome. It helps so much as a framework to support testing such as mocking out objects (so there are ‘stand-in’ objects instead of a real object.) This comes in very handy when an external service is used and certain calls are mocked to give a standard response.
At the same time, sometimes it’s really nice to have real access to the service so I know things are really working when finishing a feature and I can test it out manually.
One of these services is email. ActionMailer is great and abstracts a lot of complexities of email, but when I am testing a workflow with email, I just want email to work. Two things I always want to know:
- Is the mail server connected properly to my server?
- Can I send mail from my server to another email account?
Mail Server Connected?
The easiest way to make sure the mail server is connected is to follow the mail provider’s setup instructions. Most follow the IETF SMTP standard.
Sometimes, I don’t have an account setup, or I just want to send a few emails to test. What to do then?
I use Gmail as my mail server! (Make sure you use app passwords!)
Instructions to setup Gmail as your mail server in Rails can be found here, but I will make a copy here so I have a reference for myself.
ActionMailer Settings
Simply, make sure the ActionMailer SMTP settings are like so:
1
2
3
4
5
6
7
8
9
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com", # note: this can be any domain
user_name: "xyz@gmail.com",
password: "yourpassword",
authentication: :plain,
enable_starttls_auto: true
}
If the company is using Google Apps for business, the company’s
account in place of the gmail account (i.e. user_name:
"employee@company.co") will work as well.
Can I send Emails from Rails?
Now that the email server is connected to the Rails server, how can I test this easily without writing up a whole app?
Rails Console!
Yup, there’s a quick (almost) one liner to send email from Rails console! This is perfect for me to test out the server connection and that the email server is authenticating properly:
1
2
3
4
ActionMailer::Base.mail(from: "test@example.co",
to: "valid.recipient@domain.com",
subject: "Test",
body: "Test").deliver_now
Once this works, I know my rails server is setup with email working and now I test the email feature of the server.
Conclusion
So, that’s it, just one configuration setup and one (long) line to put a Rails server on another mail server and to test its connection.
Side note: use app passwords!
It’s a bit dangerous since the Gmail ID and password used for their SMTP server will provide full access to your Google account. So, I always make sure to create an app password for any other service I hook up that requires my Google ID and password. That way, I don’t leave my regular password around, and I can revoke the app password after I’m done testing.