How To Use Sendgrid In Rails

When sending emails through your Rails application, SendGrid is a trustworthy and strong choice. It offers a cloud-based system for sending emails that can adjust to your needs. In this blog post, we will guide you through the process of utilizing SendGrid in Rails.

Step 1: Sign Up For SendGrid

The first step, of course, is to sign up for SendGrid. You can start with a free account which allows you to send a limited number of emails per day.

Step 2: Install SendGrid gem

After signing up, the next step is to install the SendGrid gem in your Rails application. Add the following line to your Gemfile:

gem 'sendgrid-ruby'

Then run the bundle install command to install it:

bundle install

Step 3: Set up the SendGrid API Key

Next, you need to configure your SendGrid API key. You can get your API key from the SendGrid dashboard. Once you have your API key, add it to your application’s environment variable. You can do this by adding the following line in your application’s config/application.rb file:

ENV['SENDGRID_API_KEY'] = 'your_sendgrid_api_key'

Step 4: Configure Action Mailer

Now, let’s configure your Rails application to send emails via SendGrid. Add the following configuration to your config/environments/production.rb file:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :user_name => 'apikey', # This is the string literal 'apikey', NOT the ID of your API key
  :password => ENV['SENDGRID_API_KEY'], # This is the secret sendgrid API key which was previously set
  :domain => 'yourdomain.com',
  :address => 'smtp.sendgrid.net',
  :port => 587,
  :authentication => :plain,
  :enable_starttls_auto => true
}

Make sure to replace ‘yourdomain.com’ with your actual domain.

Step 5: Send an Email

Now that everything is set up, you can send an email using the mail method from your Rails application:

class UserMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome to our awesome site')
  end
end

In this simple example, we’re sending a welcome email to a new user. Congratulations, you’re now sending emails with SendGrid in Rails!

Conclusion

In this blog, we discussed how to use SendGrid in Rails. Remember to always keep your SendGrid API Key secure and do not expose it in your application’s code. Happy mailing!