DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Sending Emails with Ruby

Sending Emails with Ruby

Learn how to send emails with Ruby.

Alexandra Danchenko user avatar by
Alexandra Danchenko
·
Jun. 13, 22 · Tutorial
Like (2)
Save
Tweet
Share
4.20K Views

Join the DZone community and get the full member experience.

Join For Free

Let’s say you have a working Ruby app and need to add an email delivery functionality to it. This could be related to user authentication, or any other kind of transactional email, it makes no difference. This tutorial is tailored is aimed at helping you implement sending emails with Ruby.

Options For Sending an Email in Ruby

Mostly, you can pick one of the three options. 

The simplest one is using Net::SMTP class. It provides the functionality to send email via SMTP. The drawback of this option is that Net::SMTP lacks functions to compose emails. You can always create them yourself, but this takes time.

The second option is to use a dedicated Ruby gem like Mail, Pony, or others. These solutions let you handle email activities in a simple and effective way. Action Mailer is a perfect email solution through the prism of Rails. And, most likely, this will be your choice. 

The third option is class Socket. Mostly, this class allows you to set communication between processes or within a process. So, email sending can be implemented with it as well. However, the truth is that Socket does not provide you with extensive functionalities, and you’re unlikely to want to go with it. 

Now, let’s try to send an email using each of the described solutions. 

How to Send Emails in Ruby via Net::SMTP

From my experience, the use of that option in a regular web app is uncommon. However, sending emails via Net::SMTP could be a fit if you use mruby (a lightweight implementation of the Ruby language) on some IoT devices. Also, it will do if used in serverless computing, for example, AWS Lambda. Check out this script example first and then we’ll go through it in detail.

Ruby
 
require 'net/smtp'
message = <<END_OF_MESSAGE
From: YourRubyApp <info@yourrubyapp.com>
To: BestUserEver <your@bestuserever.com>

Subject: Any email subject you want

Date: Tue, 02 Jul 2019 15:00:34 +0800

Lorem Ipsum

END_OF_MESSAGE

Net::SMTP.start('your.smtp.server', 25) do |smtp|

  smtp.send_message message,

  'info@yourrubyapp.com',

  'your@bestuserever.com'

end

This is a simple example of sending a textual email via SMTP (official documentation can be found here. You can see four headers: From, To, Subject, and Date. Keep in mind that you have to separate them with a blank line from the email body text. Equally important is to connect to the SMTP server. 

Net::SMTP.start('your.smtp.server', 25) do |smtp| 

Naturally, here will appear your data instead of ‘your.smtp.server‘, and 25 is a default port number. If needed, you can specify other details like username, password, or authentication scheme (:plain, :login, and :cram_md5). It may look as follows:

`Net::SMTP.start('your.smtp.server', 25, ‘localhost’, ‘username’, ‘password’ :plain) do |smtp|`

Here, you will connect to the SMTP server using a username and password in plain text format, and the client’s hostname will be identified as localhost.

After that, you can use the send_message method and specify the addresses of the sender and the recipient as parameters. The block form of SMTP.start (`Net::SMTP.start('your.smtp.server', 25) do |smtp|`) closes the SMTP session automatically.

In the Ruby Cookbook, sending emails with the Net::SMTP library is referred to as minimalism since you have to build the email string manually. Nevertheless, it’s not as hopeless as you may think. Let’s see how you can enhance your email with HTML content and even add an attachment.

Sending an HTML Email in Net::SMTP

Check out this script example that refers to the message section.

Ruby
 
message = <<END_OF_MESSAGE
From: YourRubyApp <info@yourrubyapp.com>
To: BestUserEver <your@bestuserever.com>
MIME-Version: 1.0
Content-type: text/html

Subject: Any email subject you want

Date: Tue, 02 Jul 2019 15:00:34 +0800

A bit of plain text.

<strong>The beginning of your HTML content.</strong>

<h1>And some headline, as well.</h1>

END_OF_MESSAGE

Apart from HTML tags in the message body, we’ve got two additional headers: MIME-Version and Content-type.  MIME refers to Multipurpose Internet Mail Extensions. It is an extension of the Internet email protocol that allows you to combine different content types in a single message body. The value  MIME-Version is typically 1.0. It indicates that a message is MIME-formatted. 

As for the Content-type header, everything is clear. In our case, we have two types – HTML and plain text. Also, make sure to separate these content types using defining boundaries.

 Except for MIME-Version and Content-type, you can use other MIME headers:

- Content-Disposition – specifies the presentation style (inline or attachment)

- Content-Transfer-Encoding – indicates a binary-to-text encoding scheme (7bit, quoted-printable, base64, 8bit, or binary).

Sending an Email with an Attachment in Net::SMTP

Let’s add an attachment, such as a PDF file. In this case, we need to update Content-type to multipart/mixed. Also, use the pack("m") function to encode the attached file with base64 encoding.

Ruby
 
require 'net/smtp'
filename = "/tmp/Attachment.pdf"
file_content = File.read(filename)
encoded_content = [file_content].pack("m")   # base64
marker = "AUNIQUEMARKER"

After that, you need to define three parts of your email.

Part 1 – Main Headers

Ruby
 
part1 = <<END_OF_MESSAGE
From: YourRubyApp <info@yourrubyapp.com>
To: BestUserEver <your@bestuserever.com>
Subject: Adding attachment to email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary = #{marker}
--#{marker}
END_OF_MESSAGE

Part 2 – Message Action

Ruby
 
part2 = <<END_OF_MESSAGE
Content-Type: text/html
Content-Transfer-Encoding:8bit
A bit of plain text.
<strong>The beginning of your HTML content.</strong>
<h1>And some headline, as well.</h1>
--#{marker}
END_OF_MESSAGE

Part 3 – Attachment

Ruby
 
part3 = <<END_OF_MESSAGE
Content-Type: multipart/mixed; name = "#{filename}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename = "#{filename}"
#{encoded_content}
--#{marker}--
END_OF_MESSAGE

Now, we can put all the parts together and finalize the script. That’s how it will look:

Ruby
 
require 'net/smtp'
filename = "/tmp/Attachment.pdf"
file_content = File.read(filename)
encoded_content = [file_content].pack("m")   # base64
marker = "AUNIQUEMARKER"
part1 = <<END_OF_MESSAGE
From: YourRubyApp <info@yourrubyapp.com>
To: BestUserEver <your@bestuserever.com>
Subject: Adding attachment to email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary = #{marker}
--#{marker}
END_OF_MESSAGE

part2 = <<END_OF_MESSAGE
Content-Type: text/html
Content-Transfer-Encoding:8bit
A bit of plain text.

<strong>The beginning of your HTML content.</strong>
<h1>And some headline, as well.</h1>
--#{marker}
END_OF_MESSAGE

part3 = <<END_OF_MESSAGE
Content-Type: multipart/mixed; name = "#{filename}"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename = "#{filename}"
#{encoded_content}
--#{marker}--
END_OF_MESSAGE

message = part1 + part2 + part3
begin
  Net::SMTP.start('your.smtp.server', 25) do |smtp|
    smtp.send_message message,
    'info@yourrubyapp.com',
    'your@bestuserever.com'
  end

Can I Send an Email to Multiple Recipients in Net::SMTP?

Definitely, you can. send_messageexpects second and subsequent arguments to contain recipients’ emails. For example, this:

Ruby
 
Net::SMTP.start('your.smtp.server', 25) do |smtp|
  smtp.send_message message,
  'info@yourrubyapp.com',
  'your@bestuserever1.com',
  ‘your@bestuserever2.com’,
  ‘your@bestuserever3.com
end

Best Ruby Gems for Sending Emails

In the Ruby ecosystem, you can find specific email gems that can improve your email sending experience.

Ruby Mail

This library is aimed at giving a single point of access to manage all email-related activities including sending and receiving emails.

Pony

You might have heard a fairy tale about sending an email in one command. Hold on to your hats, 'cause it’s real and provided by Pony gem. 

ActionMailer

This is the most popular gem for sending emails on Rails. In case your app is written on top of it, ActionMailer will certainly come up. It lets you send emails using mailer classes and views. 

Using Mailtrap to Test Email Sending with Net::SMTP

The setup is very simple. Once you’re in your demo inbox, copy the SMTP credentials on the SMTP Settings tab and insert them into your code. Or you can get a ready-to-use template of a simple message in the Integrations section. Just choose a programming language or framework your app is built with. 

Ruby
 
require 'net/smtp'
message = <<END_OF_MESSAGE
From: YourRubyApp <info@yourrubyapp.com>
To: BestUserEver <your@bestuserever.com>
Subject: Any email subject you want
Date: Tue, 02 Jul 2019 15:00:34 +0800
Lorem Ipsum
END_OF_MESSAGE

Net::SMTP.start('smtp.mailtrap.io', 587, '<username>', '<password>', :cram_md5) do |smtp|
  smtp.send_message message,
  'info@yourrubyapp.com',
  'your@bestuserever.com'
end

If everything is alright, you’ll see your message in the Mailtrap Demo inbox. Also, you can try to check your email with HTML content and an attachment. 

You have just read the full tutorial on how to test and send emails in Ruby. Hope you enjoyed it!

HTML

Published at DZone with permission of Alexandra Danchenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • MongoDB Time Series Benchmark and Review
  • How to Use Buildpacks to Build Java Containers
  • Integrating AWS Secrets Manager With Spring Boot
  • Securing Cloud-Native Applications: Tips and Tricks for Secure Modernization

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: