DEV Community

Paul Bosorogan
Paul Bosorogan

Posted on • Edited on

Action Mailer ✉️- The Saga

Hi there! Welcome back to my channel!

If you've been following along you already know the drill, but if you're new, hello! My name is Paul and I am a future former student with Flatiron School who was on a journey to learn the basics of software engineering.

And what a journey! We learned together the pillars of web development (see blog no. 1), we later found ways to improve the functionality (responsive single page application) and visuals of simple HTML, CSS and vanilla JavaScript with React and the magic of the components (see blog no. 2).
After we managed to understand the frontend side, we dug deeper wink-wink and we entered the world of Ruby (see blog no. 3). Going forward we learned how to "tame" this beast with Rails (see blog no. 4) and how we can put it to good use by either building a full-stack application or just the backend.

For the current blog post, I have chosen to talk about a new subject that was not included in the Flatiron School curriculum.

Image description

Action Mailer ✉️

What is Action Mailer? Ruby's little gem that helps us to send emails from within the application using the mailers classes and views. If you've been juggling with Ruby and Rails for a while, then you must be very familiar with models and controllers. Well, the mailers are very similar to controllers!

Mailers inherit from the class ActionMailer::Base and can be found in the app/mailers folder.

Ready? Set! Mail!

One very easy way to generate a mailer is by running the following command:

Image description

Source

Now of course there are plenty of other materials on this platform and others that take you step by step with instructions on how to use it. But, this blog is intended to give my personal experiences following them.

The official documentation can be found here: Action Mailer Basics.

Writing the email template

Alrighty, lets get going! Now that we have the application, we might want to send an email after a new user has registered (as most websites and applications do).

How do we do that?

Inside the class UserMailer we add the following code:

class UserMailer < ApplicationMailer
  default from: 'example@gmail.com'

  def welcome_email
    @user = params[:user]
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end
Enter fullscreen mode Exit fullscreen mode

Legend:

  • default - is a method that sets the default value for all emails sent from this mailer.

  • mail - is the actual method that creates the email message.

Disclaimer
After looking over many materials, blogs and google search - it is very indicated to use a valid email address for this! Otherwise we won't be able to use it.

Further, we have to create the mailer view a.k.a the mail template. Inside the app/views/user_mailer* we will create a file welcome_email.html.erb. It should look like this:

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to example.com, <%= @user.name %></h1>
    <p>
      You have successfully signed up to example.com,
      your username is: <%= @user.login %>.<br>
    </p>
    <p>
      To login to the site, just follow this link: <%= @url %>.
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Source

Attention
The file name must match the method name inside the UserMailer.
P.S Feel free to change text as required.

Another best practice is to create a mirrored template but as a text. Not all clients like HTML emails so sending both can save us some headaches.

For that we will go ahead and create a new file welcome_email.text.erb in the same folder app/views/user_mailer with the following text:

You have successfully signed up to example.com,
your username is: <%= @user.login %>.

To login to the site, just follow this link: <%= @url %>.

Thanks for joining and have a great day!
Enter fullscreen mode Exit fullscreen mode

Now, let's take a look at the folder app/views/layouts. We will be adding 2 files: ** mailer.html.erb** and mailer.text.erb.

Inside the html type add:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

..and inside the text:

<%= yield %>
Enter fullscreen mode Exit fullscreen mode

Perfect!

Paging Mailer

We will call the mailer from inside the UserController by having the following code:

class UsersController < ApplicationController

  # POST /users or /users.json
  def create
    @user = User.new(user_params)
    if @user.save
        # Tell the UserMailer to send a welcome email after save
        UserMailer.with(user: @user).welcome_email.deliver_now
         session[:user_id] = @user.id
         render json: @user, status: created
      else
         render json: {errors: @user.errors.full_messages}, status: :unprocessable_entity
      end
   end
end
Enter fullscreen mode Exit fullscreen mode

Source

Preview the email

It's really helpful (and highly advised) to use console in your coding process. For frontend we use console.log and for the backend we use rail c. But it would be nice to see the email as well, right?

Good news! We can.

If we use the generator for the mailer (and we don't add --no-test-framework) we will notice we have an additional folder test/mailers/previews/user_mailer_preview.rb.

Inside this file we will be adding this block of code:

class UserMailerPreview < ActionMailer::Preview
  def welcome_email
    UserMailer.with(user: User.first).welcome_email
  end
end
Enter fullscreen mode Exit fullscreen mode

Now comes the fun part! And by fun I mean my own experience to try and make it work..

Inside the config/application.rb folder make sure to uncomment or add the line require "action_mailer/railtie", then a few scrolls below inside the Application class add the line: config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews".

Jumping from the application.rb folder into the config/environments/development.rb we will have the following addition:

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address:              'smtp.gmail.com',
port:                 587,
domain:               'example.com',
user_name:            'example@gmail.com',
password:             '**App Password**',
authentication:       'plain',
enable_starttls_auto: true }
Enter fullscreen mode Exit fullscreen mode

Disclaimer

  1. To configure your Mailer with GMAIL I suggest reading more from Tuyen Ha's blog .

  2. Be sure to have a working email address (don't forget the @gmail.com and paste the password as given from the Google Account security setting - see below for details).

  3. Absolutely follow this tutorial on how to keep your information safe in the development environment: Gmail Deployment + Safety instructions

Now. Hoping we have everything set and in place we can go to http://localhost:3000/rails/mailers and we should be able to see the following:

Image description

As HTML

Image description

..and as text

Image description

Ta-daa!

Conclusion

I really hope this works out and has the Action Mailer up and running! As with every other subject, these posts barely scratch the surface. There are so many ways to use it and as many ways to play around with them.

P.S. if you find yourself in a sticky situation and find a solution, share your experience with your fellow coders because sharing is caring!

Until next time, Happy coding!

Top comments (2)

Collapse
 
pimp_my_ruby profile image
Pimp My Ruby

Hi! Thanks for sharing :)

Collapse
 
paulxcodes profile image
Paul Bosorogan

Happy to share my knowledge!