An Introduction to Ruby on Rails-Action Mailer

Image for post
Image for post

The program I wrote for my company can now generate, store, associate and differentiate between leads in the dataset. And now, when someone RSVP’s to a hiring event, they receive a ticket. This ticket contains the event name, the date, the location, the attendee’s name, a confirmation number and most importantly a QR code that contains that attendee’s specific one time password secret key. Once scanned, the specific RSVP instance associated with that otp_secret_key destroys it’s child ticket instance, ensuring someone cannot check in with the same QR code twice.

Note: I will cover QR code generation, encoding and decoding in future blog posts.

Now that I have the tickets being generated with the appropriate data, how can I ensure that the attendee gets their ticket? They will need this ticket in order to be checked in on the day of the event. I was originally generating the tickets in the front end. As soon as they submit their RSVP form, if all the data is valid, their ticket is rendered as a modal, containing all of the pertinent information, including the QR code. While this would work and the QR code would scan and check in the attendee, this means the person would have had to take a screenshot or their ticket modal for later use. This didn’t seem very user friendly. I thought about what I usually experienced whenever I buy tickets. Well, I usually receive an email immediately after purchase that contains my ticket, including the QR code. How can you automatically send an email, containing unique information, immediately after an object is created and stored in your database?

If you’re using Ruby on Rails for your backend, Action Mailer is the way to go!

Before you start generating your mailers, you’ll need to configure your development environment. This will ensure that the host you’re using will actually send the emails, otherwise you will be creating Mailer objects without actually sending them to their destinations.

Image for post
Image for post

First, you need to go to your config folder (below your bin folder), then your environments folder, then choose development.rb.

Once you’re in your development.rb file, you’ll find this line:

config.action_mailer.raise_delivery_errors = false

I recommend changing the value to true, this way if you have trouble sending an email, rails will raise an exception describing the issue. While your program can work with the value set to false, I don’t really see any merit in not showing errors should an error occur.

Next, you’ll need to configure your action mailer delivery method as an smtp server to ensure that your Mailer objects are actually sent out. Do this at the bottom of your file just above the last end. This is done with one line of code:

config.action_mailer.delivery_method = :smtp

Next, underneath that line, you’ll need to configure your action mailer delivery smtp settings. This is what authenticates your account so you can actually use a provided smtp server, like Google (which I used). Then you will need to declare your host (for development purposes, I used localhost:3000. Here is what your code should look like:

Image for post
Image for post

For now, don’t get caught up with all the details. The important takeaway is your username, password, and authentication. Plain authentication is used when there is no extraneous authentication processes, such as third party authentication and OAuth. Your username and password should be the email address and password that you use for your gmail account.

The use of environment variables is important, especially if you’re pushing your code to GitHub. Much like an API key, your username and password are unique to your account and should not be public. This ensures nobody uses your credentials to access your account. To do this, I simply made a local_env.yml file in my config folder. Then included this file in my gitignore.

Image for post
Image for post

Once your environment is configured properly, you can start generating your mailers!

Mailers work much like your controllers, they communicate information from the client’s requests to your models. Your models then communicate to your views to display the data. But instead of generating a controller, what you want to do is generate a specific mailer. This is accomplished using:

rails g mailer [NAME] [METHOD] [options]

The name will correspond to the name of the mailer (much like the name would correspond to the name of a controller) and the method will correspond to the name of the email. If you want to learn more about the options, simply type rails g mailer in your terminal with no name or methods. It should look something like this:

Once you’ve generated your mailer, you will see that a lot of files were created. Most notably, a mailers folder, application_mailer.rb and whatever mailer you generated, in my case, company_lead_rsvp_ticket_mailer.rb. This is where you will put your method that actually creates the mailer object.

Image for post
Image for post

But how is your mailer going to know about the instance you’re trying to create an email for? Something is going to have to communicate with the mailer to pass along information in order to create an email that corresponds to a newly created instance of a ticket. Sounds like a job for our controller!

It is in the create method of your controller where you will also instantiate a corresponding mailer object. Here’s how it looked for my program:

Image for post
Image for post

There is a lot going here, but the important syntax to pay attention to is the respond_to which looks like a loop but is actually just calling the method in your mailer on your newly created object if that object was successfully saved. It is also meant to format different versions of the same object, one is HTML and one is JSON. The HTML format is for rendering purposes, and the JSON format is for my API. I haven’t found these parts to be too important for my use case other than their presence (I tried generating emails without the format lines and it just broke). So while it’s not vital to understand these lines, it is vital that you include them in your code.

When you call the method with your mailer class, you need to include the object you just created and then pass that object into the method.

company_lead_rsvp_ticket(@company_lead_rsvp_ticket) in your controller will correspond to company_lead_rsvp_ticket(ticket) in your mailer class.

And .deliver_now is an action mailer function that will deliver the email immediately after creation. You can also use .deliver_later and incorporate a queue method to send your email at a specific time, but I’ll save that for another blog post. If you would like to pursue it yourself, here is a great link! And here is another!

Congratulations! You’ve just completed the two most complicated steps in using Action Mailer! All that’s left now is actually rendering the message! Hm, where should we go if we want to render our data? Or rather, if we want to view it? To view something? View Something? View…

Image for post
Image for post

Yes. Your views.

Remember when you first generated the mailer? Remember how it created all those extra files? Well, one of them was a view file specifically for your new mailer! If you go to your views folder, you should see a new folder with the name of your mailer. In that folder is an html.erb file and a text.erb file named after your mailer. These two files will have identical content.

Image for post
Image for post
from company_lead_rsvp_ticket.html.erb

The plain text file can be used if the html file is taking too long render or if for any reason it doesn’t properly load. This will come in handy for another file that was created when you generated your mailer: your preview.rb file.

Image for post
Image for post

Your preview file can be found in your test folder. Go to test > mailers > previews and then select the preview file that corresponds to your mailer (hint: it will have the same name as your mailer).

In this file you should grab an email object (I grabbed the last object in the collection so I could preview the most recently created one). Then you call the mailer method on the mailer class. This might seem confusing, because the method we wrote in our model is not a class method, but an instance method. And when we create the mailer object, we call it on an instance, not on the class. Don’t be alarmed. Action Mailer is smart enough to create a new instance of our mailer class before it calls the instance method. Your code should look something like this:

Image for post
Image for post

And if you go to the url listed above your class, you should see a link to your mail object.

Image for post
Image for post

Click on it and it should show you your most recently created mailer object how it would look as an email.

Image for post
Image for post
Note: You can view as either HTML or Plain Text in the dropdown under subject

You’ve taken all the steps to configure your environment to properly handle and send messages, you’ve generated the mailer needed to create an email and you’ve previewed what your email looks like. Now what?

Well, send some emails! How did I send my emails? Well when I got bored of RSVPing hypothetical attendees using my email, I asked my friends for their emails and signed them up for the next “event”! I also signed them up for my “mailing list”. Congratulations! You now have the ability to create spam emails.

Image for post
Image for post

And the best part is that even though I’m using Gmail’s smtp server, you can send emails to people with Yahoo accounts, Outlook, etc. Much like sending emails straight from your Gmail, anyone with connection to the internet can receive an email regardless of their account provider.

This was one of my more heavier blog posts. And action mailer has a lot of moving parts that will take some practice to getting used to. But if you find yourself having particular difficulty, there is a great YouTube tutorial provided by The Pragmatic Studio that helped me out a lot! There is also no shortage of documentation online.

For more information on sending emails using Ruby, read the full guide on sending emails with Ruby, courtesy of Mailtrap.io.

Written by

UI Engineer at Analytic Partners 📲 💻 📈 | Dog Lover 🐶

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store