sending emails is my favorite thing

Rails – Sending automated emails with Devise and SendGrid on Heroku

So someone at my office forgot their password for the application I built and tried to reset it.  They were greeted with an error.  Turns out I should have actually set up the application to send automated emails, so let’s do that now….

We’ll start off by adding an email add-on in Heroku.  I chose SendGrid since it will allow me to send 1,200 emails each month for free, way more than I believe I’ll need for quite some time.

sengrid-on-heroku

Once you have it installed as an add-on (you may have to enter your credit card number for it to work, but you won’t be charged), we need to set it up to run in our application.  We’ll first need an API from SendGrid.  You can find the full instruction page  here but I’ll summarize it below:

Click here to enter your SendGrid Account.  In the top right corner click on the button labeled “Create API Key” and then on “General API Key” below it.

create-sendgrid-api-key

Next you’ll name your API key and configure the settings for it.  Where I could I set permissions to “full access” and then where I couldn’t I set it to “read access”.

sendgrid-api-settings

You’ll then be shown your new API Key, copy it and store it in a text file for when you need it in a second.

Now, in your IDE we’ll configure out application to work with SendGrid.  In you command line type in the following:
Command Line
$ heroku config:set SENDGRID_API_KEY=paste_your_api_key_here

You should now be able to view your username and password by typing in:
Command Line
$ heroku config

Now we just need to setup our application configurations for Devise to utilize SendGrid in Heroku.  First we’ll update our devise initialiazer. Here we’ll set the email address that all outgoing mail will be sent from:
config/initializers/devise.rb
config.mailer_sender = "mail-to-send-from@email.com"

Next we’ll configure our production environment to be able to send emails.


config/environments/production.rb
config.action_mailer.default_url_options = { :host => 'your_app.herokuapp.com' }
ActionMailer::Base.smtp_settings = {
  :address          => "smtp.sendgrid.net",
  :port             => "25",
  :authentication   => :plain,
  :user_name        => ENV['SENDGRID_USERNAME'],
  :password         => ENV['SENDGRID_PASSWORD'],
  :domain           => ENV['SENDGRID_DOMAIN']
}

Now we’ll commit all of our changes to our GitHub account and Heroku repositories:
Command Line
$ git add -A
$ git commit -m “updated application to utilize SendGrid in Heroku”
$ git push
$ git push heroku master

Now whenever someone asks to reset their password – they’ll actually receive an email with a link to do so instead of the application failing and asking the user to check the logs. Better late than never, right?

Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *