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

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now