How to Send Emails with Action Mailer and SendGrid in Rails 6

What is ActionMailer?

Action Mailer allows you to send email from your application using a mailer model and views. It’s the easiest way to send email through your Rails application

Why I use SendGrid?

SendGrid provides a very simple API to send transactional and marketing emails. It doesn’t make you install complicated gems or Heroku add-ons. It uses SMTP for its sending protocol and it simply just works.

How to use it in Rails?

1. Sign up for SendGrid account

First, create an account on SendGrid and you will receive a verification email. You should see the dashboard after clicking on the verification link in the email.

You can send up to 100 emails a day on a free plan. More about plans you can find here

2. Generate API key

There are two ways to connect to SendGrid. The first way is to just connect by your username and password, but a better solution is to create a SendGrid API key and set the credentials with the key instead.

3. Configure ActionMailer to Use SendGrid



specify your ActionMailer settings to point to SendGrid’s servers.

ActionMailer::Base.smtp_settings = {
	address: '',
	port: 587,
	domain: '',
	authentication: :login,
	enable_starttls_auto: true

#if you are using the API key
ActionMailer::Base.smtp_settings = {
	domain: 'YOUR_DOMAIN.COM',
	address:        "",
	port:            587,
	authentication: :plain,
	user_name:      'apikey',
	password:       ENV['SENDGRID_API_KEY']

If you are using the dot-env rails gem, make sure to add your credentials to the environment file.



4. Send your credentials to your production environment.

If you are using Heroku to deploy, don’t forget to set the credentials in your terminal, so they’re visible on your production environment

heroku config:set SENDGRID_API_KEY=api_key

5. You’re now ready to send an email!

Generate a Mailer class and watch SendGrid do the rest.