How to create a mail merge template with Ruby

How to create a mail merge template with Ruby

7 min read
Tags:

Mail merge is the process of using a template to send similar emails to multiple recipients while keeping the content personalized.

Why is Mail Merge important? Well, using a template you can modify  the content and then send the emails, but what happens when you have 3000 recipients? Copy and paste is not a scalable solution. For high-volume sends, using a mail merge template is the way to go!

In this post we will use Gmail as our email service provider to create a mail merge template with Ruby. With the Nylas Email API, we can easily support utilizing a mail merge template to send communications. Let’s explore how in this blog post.

Is your system ready?

If you already have the Nylas Ruby SDK installed and your Ruby environment configured, continue reading this blog.

Otherwise, I would recommend that you read the post How to Send Emails with the Nylas Ruby SDK to understand the setup basics.

What are we going to talk about?

What our Mail Merge Template will look like

Before we jump into the code, let’s see how our application actually works. Although for that, we need to complete a very important step, which is creating a .csv file containing all the emails and information that we’re going to use.

The file will look like this, and you can actually choose how you name it:

NameLast_NameAccountAddressEmailGift
AlvaroTejada Galindo12345742 Evergreen Terrace[email protected]Deadpool Action Figure
BlagTejada Galindo56789430 Spalding Way[email protected]AFI Poster
Alvaro aka “Blag”Tejada Galindo464511024 Cherry Street[email protected]Tomb Raider Game

Keep in mind that you can add whatever you like here or you can even delete columns. The only ones that are required for each row are the Name and Email columns.

This is what our application will look like:

Mail Merge Template application

Here, we can fill in the subject, and the body and click ‘Choose File’ to select the .csv file we created. 

If we don’t specify all the fields, we will get an error message:

You must specify all fields

The interesting part here is how we define the subject and the body.

Filling out our Mail Merge Template

Here, {Name}, {Account}, {Address} and {Gift} will be replaced by the values stored on the .csv file. So each recipient will get a personalized email. Just keep in mind that the values used between brackets need to match the column names in the .csv file.

Let’s click Submit and see what happens.

Emails sent confirmation

We have successfully sent emails to all recipients. Let’s check their inbox.

User 1 receive the email
User 2 receive the email
User 3 receive the email

As we can see, all recipients received a personalized email, as all the fields were replaced accordingly. This is what creating a Mail Merge template is all about.

Installing the Sinatra package

As we want to create a Ruby web application, our best option is to use Sinatra, one of the most popular Micro Frameworks in the Ruby world. We might need to install some additional gems:

$ gem install sinatra
$ gem install webrick
$ gem install sinatra-flash

Once installed, we’re ready to go:

First, we’re going to create a folder called MailMerge, and inside we’re going to create another folder called views.

Let’s create a file called MailMerge.rb in the MailMerge folder, and add the following code:

# Import your dependencies
require 'sinatra'
require 'csv'
require 'dotenv/load'
require 'nylas'
require 'sinatra/flash'

# Use sessions
enable :sessions

# Initialize your Nylas API client
nylas = Nylas::API.new(
    app_id: ENV["CLIENT_ID"],
    app_secret: ENV["CLIENT_SECRET"],
    access_token: ENV["ACCESS_TOKEN"]
)

# Display emails that were sent
get '/result' do
	# Get the emails array
	@emails = params[:emails]
	erb :show_emails
end

# Main page with form
get '/' do
	# Read session variables
	@subject = session[:subject]
	@body = session[:body]
	erb :main, :layout => :layout
end

# When we submit the information
post '/' do
	# Set session variables
	session[:subject] = params[:subject]
	session[:body] = params[:body]
	if(params[:subject] == '' || params[:body] == '' || params[:mergefile] == '')
		flash[:error] = "You must specify all fields"
		redirect to("/")
	else
		# Clear session variables
		session[:subject] = ''
		session[:body] = ''
		# Get parameters from form
		subject = params[:subject]
		body = params[:body]
		mergefile = params[:mergefile]
		# Auxiliary variables
		email = ''
		emails = Array.new
		# Load CSV file
		mergemail_file = CSV.parse(File.read(params[:mergefile]), headers: true)
		# Get headers
		headers = mergemail_file.headers()
		# Go through each line of the CSV file
		mergemail_file.each{ |line|
		# Assign parameters to auxiliary variables
		subject_replaced = subject
		body_replaced = body
		# Loop through all headers
		headers.each { |header|
			# If any header matches the subject, then replace it
			if(subject.match(/{#{header}}/))
				subject_replaced = subject_replaced.gsub(/{#{header}}/, line["#{header}"])
			end
			# If any header matches the body, then replace it
			if(body.match(/{#{header}}/))
				body_replaced = body_replaced.gsub(/{#{header}}/, line["#{header}"])
			end
		}
		# Get Name and Last_Name if both exist
		begin
			full_name = line["Name"] + line["Last_Name"]
		rescue => error
		# Get Name only
			full_name = line["Name"]
		end
		# Get email and send it to an array
		email = line["Email"]
		emails.push(email)
		# Try to send an email to each email on the CSV file
		begin
			# Call the Send endpoint and send an email for each 
                        # occurrence on the CSV file
			message = nylas.send!(to: [{ email: line["Email"], name: full_name }],
                                  subject: subject_replaced, 
                                  body: body_replaced)
		rescue => error
			# Something went wrong
			puts error.message
		end
	}
	# Call the page to display sent emails
	redirect to("/result?emails=#{emails}")
	end
end

Inside the views folder, we need to create 3 different files, let’s start with layout.erb:

<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<title>Nylas' Mail Merge</title>
</head>
<body>
<% flash.keys.each do |type| %>
  <div class="flash bg-green-300 border-green-600 border-b p-4 m-4 rounded w-2/5 grid place-items-center text-red-600 font-bold">
    <%= flash[type] %>
  </div>
<% end %>	
<%= yield %>
</body>
</html>

Then, main.erb:

<div class="bg-green-300 border-green-600 border-b p-4 m-4 rounded w-2/5 grid place-items-center">
<p class="text-6xl text-center">Mail Merge</p>
<br>
<form method="post">
<label for="subject" class="font-bold">Subject: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
<input type="text" name="subject" value="<%= @subject %>" size="50"></input>
<br><br>
<label for="body" class="font-bold">Body:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
<textarea name="body" rows=5 cols=49><%= @body %></textarea>
<br><br>
<label for="mergefile" class="font-bold">Merge File: &nbsp;</label>
<input type="file" name="mergefile">
<br><br>
<button type="submit" class="block bg-blue-500 hover:bg-blue-700 text-white text-lg mx-auto py-2 px-4 rounded-full">Submit</button>
</form>
</div>

And finally show_emails.erb:

<div class="bg-green-300 border-green-600 border-b p-4 m-4 rounded w-2/5 grid place-items-center">
	<h1 class="text-3xl"> The email was sent to the following addresses</h1>
	<br>
	<% @emails = @emails.gsub(/\[|\]/,'').gsub(/\"/,'')  %>
	<% @emails = @emails.split(",") %>
	<% @emails.each do |item| %>
	<p class="font-semibold"><%= item %></p>
	<% end %>
</div>

<div class="bg-green-300 border-green-600 border-b p-4 m-4 rounded w-2/5 grid place-items-center">
<a href="/" class="text-blue-600">Go back</a>
</div>

And that’s it. We’re ready to roll.

Running our Mail Merge Template

In order to run our application, we just need to type the following on the terminal window:

$ ruby MailMerge.rb
Running our Mail Merge Template application

Our application will be running on port 4567 of localhost, so we just need to open our favourite browser and go to the following address:

http://localhost:4567

We easily created a mail merge template application using Ruby.

If you want to learn more about the Nylas Email API, please visit our documentation Email API Overview.

Sign up for your Nylas account and start building for free.

What’s Next?

Don’t miss the action, join our Livestream Coding with Nylas:

Related resources

How to customize the Nylas Scheduler workflow with custom events

We’re excited to announce the launch of the Nylas Scheduler v3! Efficient scheduling is essential…

How to block time slots in Outlook and Google calendar with Nylas Calendar API

Key Takeaways Managing calendar availability is essential for professionals, teams, and businesses to stay organized…

How to Solve Webhook Integration Challenges with PubSub Notification Channel

Key Takeaways This article addresses the challenges of webhook integration and introduces the PubSub Notification…