Rails and sending transactional emails

Yesterday I was working on configuring the default Rails mailer to work with 3rd party SMTP server providers like Gmail, Zoho and so on.

First, I tried Gmail since it gives you quota of 500 mails per day for the trial users but it is paid.

Then I remembered that we used Zoho services at NaughtySpirit and decided to give it a shot.

Rails Mailer Configuration

First of all, you have to configure your mailer to work with the SMTP server and it's an really easy task! 🤘🏻

There're 3 environment configuration files in the Project -> config -> environments directory you should edit: development.rb, production.rb and test.rb.
These files contains environment specific configurations. If we're intending to use the mailer in all of these environments - we should include its configs in these 3 files.

As you can see, I'm storing the needed information in environment config variables.
If you're using Heroku to host your web apps, you can set these config variables in the settings page within the dashboard: Personal Apps -> YOUR_APP -> Settings -> Config Variables -> Reveal Config Vars

If you're using Zoho as SMTP server for sending transactional emails, you should provide the following information:

address: smtp.zoho.eu

port: 587

domain: your domain, i.e. seishin.me

user_name: your zoho account, i.e. support@seishin.me

password: YOUR_PASSWORD

authentication: login

And that is it! So simple! 👻

What about the actual sending of emails?

First we have to generate a mailer by executing this command in the Terminal:rails generate mailer UserMailer
This will generate the following files:

All of the class variables (i.e. all of the vars with @ are passed to the erb template file. But... We don't have a template file for our welcome email, right? Now we're going to create it!
Create a file called welcome_email.html.erb in app/views/user_mailer/ with the following content:

We're almost ready now! What is next - sending an email, right? 🙂
So whenever you want to send an email and in our case it should be after the user successfully signed up, we should call the UserMailer class and pass the user object:UserMailer.welcome_email(@user).deliver_later

The two most used options for the delivery are deliver_later and deliver_now.

In Conclusion

It's not a difficult task, but you could have some issues with the SMTP configuration. You've to read throughly the SMTP provider's documentation.
As for the Rails' Mailer... It's straightforward and not so difficult to understand and use as most of the Rails functionalities. 🙃

For more information, please review the official Action Mailer Basicsdocumentation