Send emails with Postmark in Rails

December 31, 2023

If you are looking for an easy solution to setting up Action Mailer in Rails, Postmark is definitely a strong option. I have used Mailgun, Mailjet and several others, but this one is probably the easiest I have come across to set up.

Keep in mind, the free tier at Postmark only allows 100 emails per period, but that's plenty to get it set up and see if you like it.

Get a Postmark account.

Simple enough, sign up. Then set up your server (that's how they refer to sites/domains). You'll need to verify that you can send email from your domain name. Once your verified, it's onto getting this set up in Rails.

Set your verified email/domain in app/mailers/application_mailer.rb.

class ApplicationMailer < ActionMailer::Base
  default from: "[email protected]"
  layout "mailer"
end

You can use any email from your verified domain, but I recommend one that you actually have setup that can receive replies.

Add the postmark-rails gem to your Gemfile.

gem 'postmark-rails', '~> 0.22.1'

Them, run bundle install on your command line from within the app.

yourapp$ bundle install

Add your Postmark API key to your encrypted Rails Credentials file.

yourapp$ rails credentials:edit

You may have to add a Editor Wait command in your bash file, or manually do it to edit your rails credentials.

Once in the credentials file, add the Postmark API key.

postmark_api_token: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX

You get the key by clicking on your server in Postmark and then selecting the API Tokens tab. After that, simply copy your token and add it to the credentials file like above.

Update your production and development (if you want to use Postmark in development) environments.

Start with production at config/environments/production.rb and add the following.

config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :postmark
config.action_mailer.perform_deliveries = true
config.action_mailer.postmark_settings = { api_token: Rails.application.credentials.postmark_api_token }
config.action_mailer.default_url_options = { host: 'yourdomain.com' }

And then if you want to use it in development, add this into your file at config/environments/development.rb.

 # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false
# Add after you see this line above
  config.action_mailer.perform_caching = false
  config.action_mailer.delivery_method = :postmark
  config.action_mailer.perform_deliveries = true
  config.action_mailer.postmark_settings = { api_token: Rails.application.credentials.postmark_api_token }
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

And that's it. Give your Action Mailer a test.

Comments

You must be logged in to comment.