Sending Emails using SendGrid API in Rails 4.1


There are many Ruby gems available for sending emails using SendGrid API. I choose sendgrid-rails gem due to its simplicity. It was easy to setup and get it working on the production system.


Step 1

Create a SendGrid account first at :

Step 2

Add the sendgrid-rails gem to the Gemfile:

gem 'sendgrid-rails', '~> 2.0'


bundle install

Step 3

Use secrets.yml to define the SendGrid API credentials:

  sendgrid_username: your-sendgrid-username
  sendgrid_password: your-sendgrid-password

Emails are not sent in development and test environments. So you can define it only for production.

Step 4

In config/initializers/mail.rb:


ActionMailer::Base.smtp_settings = {
  :address => '',
  :port => '25',
  :domain => '',
  :authentication => :plain,
  :user_name => Rails.application.secrets.sendgrid_username,
  :password => Rails.application.secrets.sendgrid_password

Step 5

In config/initializers/mail.rb:

SendGrid.configure do |config|
  config.dummy_recipient = ''

I use my support email so that I can reply to any questions. You can use whatever email you wish for the dummy_recipient.

Step 6

Create mailer class using rails generator.

class WelcomeMailer < ActionMailer::Base
  default :from => '',
          :subject => 'An email sent via SendGrid with substitutions'

  def confirmation_email
    category 'SendGridRocks'
    mail :to => ''

Here category is used to tag the emails so that you can organize your email analytics. When you login to your SendGrid dashboard, it will be easier to analyze.

Step 7

Send email using ActionMailer as usual. It is better to send it in a background job.


Of course, you need to create the email content in app/views/welcome_mailer.html.erb and app/views/welcome_mailer.text.erb.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.