In this post, we will configure Mandrill with our Rails application to send emails. Mandrill is used for sending transactional emails whereas Mailchimp is used to send promotional emails. Here are the steps:

  1. Create an account with Mandrill.
  2. Next, click on the settings tab. Click the +New API Key button. Enter some description and click Create API Key button.
  3. Copy this key somewhere as it will be used as a password to connect Mandrill.
  4. Next, create a new Rails project ( or you may already have a project ).
  5. Add the following line in your Gemfile:
    gem 'mandrill-api'
  6. Now run bundle install to download this gem.
  7. On the command prompt, execute the following command to generate the mailer class:
    rails generate mailer mandrill_mailer

    This command will create following files and folders in your project:

    app/mailers/mandrill_mailer.rb
    app/views/mandrill_mailer
    app/views/layouts/mailer.html.erb

    There would be some other files as well.

  8. Add following lines in your config/environments/development.rb just before the end statement:
    config.action_mailer.delivery_method = :smtp
    config.action_mailer.smtp_settings = {
        :address => 'smtp.mandrillapp.com',
        :port => '587',
        :authentication => :plain,
        :user_name => 'your_email_used_for_registration_in_mandrill',
        :password => 'your_mandrill_key',
        :domain => 'localhost',
        :enable_starttls_auto => true
    }
  9. Now add following code in your app\mailers\mandrill_mailer.rb file:
    class MandrillMailer < ActionMailer::Base
    
      default(
          :from => 'your_email'
          :reply_to => 'your_email'
      )
    
     def send_email(email, subject, name)
        @name = name            # this variable will be passed to 
        mail(to: email, subject: subject)
     end
    
    end
  10. Now, we will create a template for email. This file will be created with the name of the function. Hence, create a new file app\views\mandrill_mailer\send_email.html.erb with following code:
    <html>
    <head>
    
    </head>
    <body>
        Hello <%=@name%>
    </body>
    </html>
  11. Lastly, to check our mailer, we will create a controller with a method. Execute the following command on command prompt:
    rails generate controller test mail
  12. Open the app\controllers\test_controller.rb file and add following code:
    def mail
      MandrillMailer.send_email('any_email_address', 'subject_of_email', 'name_to_pass').deliver
      render :text => 'Your email is sent!'
    end
  13. Start the server with the command:
    rails server

    and navigate to the URL:

    http://localhost:3000/static/mail

    The email should be delivered if all settings are fine.