DEV Community

Sofia Tarhonska
Sofia Tarhonska

Posted on • Originally published at

Sending Emails with Ruby on Rails

Since the server-side web application framework, Ruby on Rails, was written back in 2004, it has gained popularity as one of the most cost and time-effective solutions to build Ruby applications. If you’re developing such an app and want to understand how to send emails with Rails, this tutorial is for you.

What options do you have to send emails using Ruby on Rails?

The best part about Rails is that it’s a highly intuitive framework with many built-in Ruby gems (libraries), one of which is ActionMailer. Using mailer classes and views the gem helps add email-sending functionality to your Rails app.

This is an example of what a simple email using ActionMailer looks like:

class TestMailer < ActionMailer::Base
  default from: ''
  def simple_message(recipient)
      to: recipient,
      subject: 'Any subject you want',
      body: 'Lorem Ipsum notifications'
Enter fullscreen mode Exit fullscreen mode

Additionally, check out our how to send emails with Ruby tutorial that covers all of the other options available for Ruby apps specifically and not just those built with Rails.

How to send emails using ActionMailer?

Below we’ll go over all the steps you need to take to start sending with ActionMailer. In our example, we’ll include an attachment and HTML content.

The first step is to create a mailer model and views that your app will use.

$ Rails generate mailer Notifier
Enter fullscreen mode Exit fullscreen mode

After this, define built-in helper methods in the mailer model to generate an email message. In the mailer views, variables such as recipient address, attachments, and more can be set up.

Here’s what a script with different helpers set in it would look like:

class UserMailer< ApplicationMailer
  def simple_message(recipient)
    attachments["attachment.pdf"] ="path/to/file.pdf")
      to: “”,
      subject: "New account information",
      content_type: "text/html",
      body: "<html><strong>Hello there</strong></html>"
Enter fullscreen mode Exit fullscreen mode

How to send HTML emails?

The above mailer class example includes HTML content, so the next step that needs to be done is creating a corresponding view. This means that a template is used along with a mailer, so create a .erb file and give it the same name as the method in the mailer class.

Continuing with our above example, this would be new-account.html.erb and locate it in app/views/notifier_mailer/.

Now any HTML-formatted email can use this HTML template. You can also create a text part for this email with a new-account.txt.erb file. Just remember to fill out the email templates with actual content before sending them.

How to send emails with attachments?

As shown in our example, if you want to send an email message with attachments, all that needs to be done is to define relevant helpers in the code. These can be either regular attachments or attachments.inline helper. After that, specify the file name and its path:

  • add attachments: attachments['filename.png'] ='path/to/attachment.pdf')
  • add an inline attachment: attachments.inline['filename.png'] ='path/to/attachment.pdf')

At this stage, you’ll need to define a delivery method and do ActionMailer configuration. By default, SMTP is already set in ActionMailer and is configured with Port 25. The authentication option can be selected as one of these plain, loginor cram_md5.

Here is an example of one possible configuration:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:              '',
  port:                 25,
  domain:               '',
  user_name:            '<your username>',
  password:             '<your password>',
  authentication:       'plain',
  enable_starttls_auto: true
Enter fullscreen mode Exit fullscreen mode

Using config.action_mailer.smtp_settings, the default SMTP server can be adjusted if needed. Additionally, other delivery methods such as sendmail, file (save emails to files), and test (save emails to ActionMailer::Base.deliveries array) can be selected.

Next is the actual sending stage. Since we already defined the delivery method, did the SMTP configuration, prepared a template, and attached the file, all that needs to be done is to call deliver_now. To learn how to apply more ActionMailer delivery methods, such as deliver_now!, deliver_later, check this documentation out.

How to send bulk emails?

If you want to send emails to multiple recipients with ActionMailer, set a list of email addresses to the :to key or :cc, and :bcc headers if needed. This can be done as a single string of email addresses separated by a comma or an array list of recipients. Here is an example:

class AdminMailer < ApplicationMailer
  default to: -> { Admin.pluck(:email) },
  from: ''
  def new_registration(user)
    @user = user
    mail(subject: "New User Signup: #{}")
Enter fullscreen mode Exit fullscreen mode

How to send email using Email API?

An alternative way of having to send functionality in your Rails application is using an API offered by email service providers. This is one of the most reliable ways to set up an automated email-sending function in your app quickly and not worry about constant deliverability issues popping up.

With a service such as Mailtrap Email API, you can also get additional control over your email deliverability. The dashboards with valuable insights and up to 60 days of email logs give an accurate understanding of where your email infrastructure stands.

After a quick setup of the Email AP/SMTP Relay, your app can start sending emails hassle-free. If any issues arise, the email deliverability alerts feature will always let you know. Email API’s system automatically checks your metrics every three hours, and in case of a critical drop in a predetermined threshold, the alert is sent on an hourly basis, thus giving you even more control over email deliverability. On top of that, there are weekly reports that help understand your performance.

If you use ActionMailer in your Rails app for email-sending functionality, thanks to a custom Mailtrap delivery method, the API can also be integrated with it.

Firstly add this line to your app’s Gemfile:

$ gem install mailtrap
Enter fullscreen mode Exit fullscreen mode

Then execute:

$ bundle install
Enter fullscreen mode Exit fullscreen mode

Alternatively, install it yourself:

$ gem install mailtrap
Enter fullscreen mode Exit fullscreen mode

Now set the API key and configure the delivery method in your ActionMailer configuration in Rails projects located in config/$ENVIRONMENT.rb:

config.action_mailer.delivery_method = :mailtrap
config.action_mailer.mailtrap_settings = {
  api_key: ENV.fetch('MAILTRAP_API_KEY')
Enter fullscreen mode Exit fullscreen mode

Now ActionMailer can be used as usual with Mailtrp API as its delivery method, and you can add category and custom_variables to the mail generation if needed:

  to: '',
  subject: 'You are awesome!',
  category: 'Test category',
  custom_variables: { test_variable: 'abc' }
Enter fullscreen mode Exit fullscreen mode

For more detailed instructions and source code, check out our GitHub page.

If you choose to use the SMTP Relay instead of Email API, in your Mailtrap account, select the verified sending domain and find your SMTP server credentials in the “API and SMTP” tab.

Image description

Here is an example of how the configuration should be:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address   => '',
  :port      => 587,
  :domain    => '',
  :user_name => 'api',
  :password  => '********059a',
  :authentication => 'plain',
  :enable_starttls_auto => true 
Enter fullscreen mode Exit fullscreen mode

How to send emails using Gmail SMTP?

Being one of the leading email service providers, there is a high demand for Gmail SMTP server use. If you want to use this option with ActionMailer, here is an example code for the configuration:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address => "",
  :port => 587,
  :user_name => "your mail",
  :password => "your password",
  :authentication => :plain,
  :enable_starttls_auto => true
Enter fullscreen mode Exit fullscreen mode

Get more information on Gmail SMTP settings here.

Testing emails before sending: why and how?

Email validation in Ruby on Rails is as important as in any other framework. Whether your application is sending an automated welcome email or any other transactional email, you want to have this tested before deployment. The safest way to test email sending functionally is to use a tool specifically designed for this purpose.

Mailtrap Email Sandbox is exactly that type of tool. Using Email Sandbox, you can run safe email testing from staging and dev environments without the risk of spamming users. The Sandbox catches outgoing SMTP traffic and lets you troubleshoot and debug any issues, analyze and validate your HTML/CSS, inspect raw email data, run a spam analysis score, and so much more.

  1. To start using Email Sandbox with Actionmailer, create a free Mailtrap account in just a few clicks.
  2. Navigate to the “Sandbox” page, select the appropriate Inbox, and go to the “SMTP Settings” tab.
  3. From there, choose “Ruby on Rails” in the drop-down menu, and the relevant script will appear.
  4. Before using it with your credentials, in <em>config/environments/*.rb</em> file specify ActionMailer defaults for your development or staging servers:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :user_name => 'Your Username',
  :password => Your Password,
  :address => '',
  :domain => '',
  :port => '2525',
  :authentication => :cram_md5
Enter fullscreen mode Exit fullscreen mode

You can also send messages directly from your email client or mail transfer agent using Email Sandbox with the below credentials and your username and password in them:

Image description

Image description


Using Rails for email sending might seem challenging at first, but it’s one of the most reliable solutions. Once everything is set and tested, it works like a clock, and very few issues happen. For a deeper understanding of how to develop Rails apps with robust email delivery, check out RailsGuides.

Thank you for reading our guide! Visit Mailtrap Blog to see the original article.

Top comments (1)

citronbrick profile image

Please consider enabling syntax highlighting on your code blocks using
<3 backticks> ruby

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git