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: 'info@yourrubyapp.com'
def simple_message(recipient)
mail(
to: recipient,
subject: 'Any subject you want',
body: 'Lorem Ipsum notifications'
)
end
end

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

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"] = File.read("path/to/file.pdf")
mail(
to: “your@bestuserever.com”,
subject: "New account information",
content_type: "text/html",
body: "<html><strong>Hello there</strong></html>"
)
end

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.

To learn how to send bulk emails and email with attachment, visit this page.