Blog

How to send emails in ruby (With Examples)

Tautvydas Tijūnaitis Tautvydas Tijūnaitis
· 9 min read · Tips and resources · April 21st, 2022
Ruby is a popular open-source programming language enjoyed for it's simplicity and versatility. Learn how you can send emails in Ruby, and get advanced functionality when used with MailerSend's email API.

Ruby is a powerful, dynamic and open-source language that has a significant influence on today’s web applications. When coupled with the Ruby on Rails framework, it’s a highly capable language for building amazing web apps and database solutions. You can also use it to handle your email functionality! 

While Ruby has email functionality baked in, the features of SMTP (Simple Mail Transfer Protocol) mailing within the language are simplistic. There are other ways to send emails that provide better customization and far more features. 

In this guide, we’ll go over the different ways you can use Ruby to send emails. We’ll show you the methods you can use—along with code examples—so you can start sending emails with your Ruby project. 

Let’s dive in!

Why Use Ruby to Send Emails

Let’s assume you’re building a web app using Ruby on Rails, and you need to code email functionality that ties into user authentication or some other transactional email delivery system. Some quick research will demonstrate that there are basically three main ways to handle email with Ruby.

They are: 

  • With an SMTP server

  • Using a standalone Ruby Gem, like ActionMailer

  • Using an API, like MailerSend

Ruby has SMTP mailing built-in with the Net::SMTP class. While it certainly provides the functionality necessary to send out emails, it lacks any real email composition features. You could, of course, compose them yourself, but that’s a lot of extra and potentially ongoing work.

Your next best choice is to go with a standalone gem, such as Mail, Pony or ActionMailer. 

All of these prebuilt solutions streamline email management in Ruby, though they do require a bit more setup. That said, once they’re configured, there’s not much else to do. Of these three gems, ActionMailer is the most popular choice.

The last option is to offload your mailing to a service such as MailerSend and handle everything through an email API. It’s faster, easier and more efficient than a solution that only handles emails internally. And it is, without a doubt, far better if you need next-gen email analytics.

So let’s take a look at the two most viable and feature-filled options you have for sending emails with Ruby: ActionMailer and APIs.

Sending Emails in Ruby via ActionMailer

ActionMailer is by far the most popular gem for sending emails with Ruby. It leverages classes and views for its functionality, and the so-called mailers are similar to controllers. They inherit from ActionMailer::Base and are located in the app/mailers directory. 

Once you’ve pulled down the ActionMailer gem, the first thing you’ll do is generate a mailer:

bin/rails generate mailer User

Next, you’ll instantiate the class and provide the mailer layout:

# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: 'admin@webapp.com'
  layout 'mailer'
end

Finally, you’ll create user_mailer.rb and add:

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
end

Modifying the Mailer

Methods on mailers are called actions use views for content structuring. In comparison to a controller, which generates HTML-like content to send, a mailer creates an email message.

You can add a method to the user_mailer.rb to send a message to a registered user’s email:

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  default from: 'notifications@example.com'
  def welcome_email
    @user = params[:user]
    @url = 'http://webaoo.com/login'
    mail(to: @user.email, subject: 'Welcome to Web App!')
  end
end

To elaborate, the default method assigns default values for this specific mailer. In the above example, it’s used to set the :from header value, though you can still override these defaults for individual messages. The mail method itself generates the message, and you can use it to populate the values of the :to and :subject headers.

Creating a Mailer View

Mailer views are essentially HTML templates that you can populate with variables. To make one, create a file named welcome_message.html.erb in app/views/user_mailer/ and fill it accordingly:

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <h1>Welcome to Web App, <%= @user.name %></h1>
    <p>
      You've successfully created an account on Web App. To login and start
      doing some nice Web App things, click here: <%= @url %>.
    </p>
    <p>See you soon!</p>
  </body>
</html>

Calling the Mailer

Finally, you’ll need to call the mailer from your app. In essence, it’s no different than rendering a view—it’s just rendering and sending it through mail protocols instead of HTTP. For this reason, it’s a good idea to have your controller instruct the mailer on when to send an email, such as when a user registers.

ActionMailer is powerful, but it requires a lot of work to get going. If you want to learn more about it, the basics guide on Rail Guides is a good place to do so. Otherwise, let’s look at a much easier way to send emails in Ruby.

Sending Emails in Ruby via Email API

Even with a gem such as ActionMailer, sending emails in Ruby can be a headache. This is especially true if you want more functionality and customizations. To achieve this, a better approach—which is also more secure—is to send email using an API.

This is where MailerSend’s API comes in.

Many of the email gems are handy, but they won’t allow you to leverage advanced features and functionality. You’ll be missing out on personalization, highly-polished responsive email templates, suppression list management, and sender authentication using SPF, DKIM and DMARC security protocols, just to name a few.

Let’s take a look.

Getting Started With Ruby and MailerSend

If you want to follow along, sign up for a free account and test it out for yourself. Once you’re registered and you have your API key, go ahead and install the MailerSend gem:

gem install mailersend-ruby

Next, you’ll need to initialize the gem in your Ruby file with the required "mailersend-ruby".

The MailerSend API requires that you have a .env file with a MAILERSENDAPITOKEN variable, like so:

MAILERSEND_API_TOKEN="aSuperLongAPIKey"

Alternatively, you can enable the varial system-wide, which is useful for developing with Kubernetes or Docker containers. 

Next, let’s add the code we’ll need to generate a mail message:

require "mailersend-ruby"

# Intialize the email class
ms_email = Mailersend::Email.new

# Add parameters
ms_email.add_recipients("email" => "ron@parksandrec.com", "name" => "Ron")
ms_email.add_recipients("email" => "leslie@parksandrec.com", "name" => "Leslie")
ms_email.add_from("email" => "april@parksandrec.com", "name" => "April")
ms_email.add_subject("Time")
ms_email.add_text("Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.")
ms_email.add_html("<b>Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.</b>")

# Send the email
ms_email.send

Need some CC or BCC recipients? No problem—add them as additional parameters:

ms_email.add_cc("email" => "chris@parksandrec.com", "name" => "Chris")
ms_email.add_bcc("email" => "andy@parksandrec.com", "name" => "Andy")

Personalization

Personalization is simple with MailerSend’s API. Simply add a structure for the appropriate variables and call them in the parameters:

require "mailersend-ruby"

# Intialize the email class
ms_email = Mailersend::Email.new

# Add parameters
ms_email.add_recipients("email" => "ron@parksandrec.com", "name" => "Ron")
ms_email.add_from("email" => "april@parksandrec.com", "name" => "April")
ms_email.add_subject("Time {$test}")
ms_email.add_text("{$test} Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.")
ms_email.add_html("<b>{$test} Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.</b>")

variables = {
  email: 'ron@parksandrec.com',
  substitutions: [
    {
      var: 'test',
      value: 'Test Value'
    }
  ]
}

ms_email.add_variables(variables)

ms_email.send

And if you want to get a little fancier, you can do some advanced personalizations:

require "mailersend-ruby"

# Intialize the email class
ms_email = Mailersend::Email.new

# Add parameters
ms_email.add_recipients("email" => "ron@parksandrec.com", "name" => "Ron")
ms_email.add_from("email" => "april@parksandrec.com", "name" => "April")
ms_email.add_subject("Time {{ test }}")
ms_email.add_text("{{ test }}Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.")
ms_email.add_html("<b>{{ test }}Time is money, money is power, power is pizza, and pizza is knowledge. Let's go.</b>")

personalization = {
  email: 'ron@parksandrec.com',
  data: {
    test: 'Test Value'
  }
}

ms_email.add_personalization(personalization)

ms_email.send

Sending Templated Emails

Sending templated email messages is as simple as adding a template ID to the parameters:

require "mailersend-ruby"

# Initialize the email class
ms_email = Mailersend::Email.new

# Add parameters
ms_email.add_recipients("email" => "ron@parksandrec.com", "name" => "Ron")
ms_email.add_recipients("email" => "leslie@parksandrec.com", "name" => "Leslie")
ms_email.add_from("email" => "april@parksandrec.com", "name" => "April")
ms_email.add_subject("Time")
ms_email.add_template_id(12415125)

# Send the email
ms_email.send

As you can see, working with an API and an email service like MailerSend makes the entire process much easier. While the solution you choose to go with depends on your needs and preferences, MailerSend’s API provides everything you need to handle all your email needs and more. 

And if you ever plan on migrating away from Ruby to a different language, it’s not a problem. With a powerful infrastructure that scales quickly and works with countless languages, all linked to an intuitive interface that the entire team can understand, MailerSend is a better way to work with email.

Start Sending Emails in Ruby

There you have it: All the main ways to send email in Ruby. If you’re looking for a secure, highly customizable method to handle the email needs of your Ruby app, look no further than MailerSend. 

Sign up now for free

Get started with 3,000 emails per month.

Do you send emails in Ruby? Or do you prefer another language for your transactional email? Let us know in the comments!

Tautvydas Tijūnaitis
I'm Tautvydas, Lead Developer at MailerSend. When I'm not busy coding, I live and breathe European football—whether watching games in stadiums or building my fantasy team online!