How Action Mailer Works in Rails

Sending emails in a rails application is very easy and quite handy using action mailer. First we will go through the basic setup of action mailer then we will go in details how it works.

Step 1
  We can setup a mailer class using rails generator
  rails generate mailer UserMailer

Step 2
  Then we can create any instance method inside it.
    def welcome_email(user)
      @user = user
      @url  = 'http://example.com/login'
      mail(to: @user.email, subject: 'Welcome')
    end

Step 3
  We can call this method form model or controller or any kind of callbacks using
   Like
   UserMailer.welcome_email(@user).deliver

Step 4
  You can set up a view template for the welcome_email in side the views/mailer directory
  Like
  welcome_email.html.erb
  and you can specify the layout format here and can also access the instance variables defined in the       welcome_email(user) method

Step 5
  Additionally we can set up the smtp configuration inside our development.rb
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    domain: "abc.com",
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: ENV["GMAIL_USERNAME"],
    password: ENV["GMAIL_PASSWORD"]
 }

But this all are looks so simple to implement but there are some problem associated with it.If there is any error sending this email rails by default does not show any error in the application for that you need to change your development.rb file

From 
  config.action_mailer.raise_delivery_errors = false
To 
  config.action_mailer.raise_delivery_errors = true

So that rails will show error if there is any problem sending emails.

And again if you looks deeply the code you can see that we are calling the welcome_email method directly using the class name (UserMailer.welcome_email(@user).deliver) so conventionally it should be a class method but inside the UserMailer class its a instance method so there is some magic ;)

After I go through the rails source code i have found that every action mailer inherited from ActionMailer::Base  So if you open the actionmailer/lib/action_mailer/base.rb file

There is one method named as method_missing which creates the magic by calling the new instance of the method and by this way it works for more details please check the rails source code.

Comments

Popular posts from this blog

Debug Nodejs inside docker container

Swap primary keys between two records in the same table in Postgres

How to add a bootstrap table with fixed header and scrollable body