Last Updated: September 09, 2019
·
835
· dylans

Sending emails in the background with Iron

You almost always want to send emails to your users in a background process. Your end-user shouldn't have to wait until your system makes a request to your mail provider, does a handshake, then waits for the sending of the mail to complete. Here's a quick and smart way to send emails via Sendgrid to your users using Iron's Worker product using Ruby. Since Worker is Docker based, you can use any programming language you want. That's one of the benefits of using Iron vs other background job systems.

In a new directory, create a Gemfile with the following:

source 'https://rubygems.org'
gem 'sendgrid-ruby'
gem 'iron_worker', '>= 3.0.0'

Create the Ruby file, send_email.rb, that will send your emails for you:

We're using this approach here as we're using the Iron CLI. You'd probably want to send the payload in programatically using one the Iron Ruby Gem.

require_relative 'bundle/bundler/setup'
require 'iron_worker'
require 'sendgrid-ruby'
include SendGrid

from = Email.new(email: IronWorker.payload["from"])
to = Email.new(email: IronWorker.payload["to"])
subject = IronWorker.payload["subject"]
content = Content.new(type: 'text/plain', value: IronWorker.payload["body"])

mail = Mail.new(from, subject, to, content)
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.headers

Create a payload.json file that will contain the data that you'll send to your Ruby program.

{
  "from": "test@example.com",
  "to": "you@example.com",
  "subject": "It works!",
  "body": "Hello from IronWorker"
}

Now you need to install the dependencies using Docker, zip up your code, and upload it to Iron.

Note that in this example you'll use Iron's own Ruby based Docker image for convenience. You can use definitely use your own images if you'd like.

> docker run --rm -v "$PWD":/worker -w /worker iron/ruby:dev bundle install --standalone --clean
> zip -r email_worker.zip .
> iron worker upload -e SENDGRID_API_KEY=YOUR_SENDGRID_API_KEY --name email_worker --zip email_worker.zip iron/ruby ruby send_email.rb

Once your code is uploaded to Iron, you can send emails anytime you'd like. Here's how to send an email via the Iron CLI:

> iron worker queue --payload-file payload.json --wait email_worker

You should see some output that looks like the following:
iron email

Conclusion

Using Iron's Worker product is a great way to run background tasks. It's language agnostic, runs within its own container, and can scale up without the end user needing to worry about infrastructure. It's available on all public clouds and on-premise, so you never have to worry about being locked to one cloud vendor.