Email notifications using Rails ActionMailer

The eighth week of GSoC 2016 coding period is over and I got to work on something new in Rails. This time I was making the email notification system for the Q & A system so that when a user posts a question or answer related people get notified via emails.

Rails has has email delivery framework called ActionMailer. Though I was familiar with Rails, I haven’t worked on ActionMailer before this. So the first thing to do was checking the ActionMailer documentation. I strongly recommend following this  documentation to  understand the email delivery system. Rails guides have good documentation for each version of Rails and the features well explained. It’s a good place to start with.

I had to create a new AnswerMailer and modify the existing CommentMailer and SubscriptionMailer to send out email notifications to users.

A Mailer basically contains some methods that defines the recipient and the subject of the mail to be sent along with the delivery method. It inherits from ApplicationMailer which basically contains the default sender mail address. The mailer view template goes under the views directory which is the standard template directory for Rails. The view template is named according to the mailer method. So for AnswerMailer if there is a method named notify_question_author the template would go with the name notify_question_author.html.erb in the views/answer_mailer directory. Whatever content you want to send in the email goes in this email. So you see the naming convention and functioning quite is similar to Rails controller though not the same.

To send a mail you need to call the mailer method from the controller as described here. Now you need to send mail on specific conditions. Like when you create a post, for example, you would want the subscribers to get specific content while when you post an answer to a question you would like to notify the question followers as well who asked the question. So it is good to create a class or an instance method in related model to do so. Like I defined a instance method answer_notify() for Answer model that notifies the question author as well  as users who liked the question. This contained  two mailer methods AnswerMailer.notify_question_author() and AnswerMailer.notify_answer_likers() which sent emails on meeting some specific conditions. So this way you can frame a custom method that sends the mail and suits the conditions as well keep the code in the controller simple an let the Model contain the method description.

You can find my entire work on this in plots2 PR #612.