Skip to content

Instantly share code, notes, and snippets.

@DeepNeuralAI
Last active April 24, 2019 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeepNeuralAI/b56f45ba980aed4650625765a165297c to your computer and use it in GitHub Desktop.
Save DeepNeuralAI/b56f45ba980aed4650625765a165297c to your computer and use it in GitHub Desktop.
Rails - Mailer

Rails - Mailer

From Scratch (Optional)

rails new new_app_name
rails g scaffold user name:string email:string
rails db:migrate

ActiveMailer

Action Mailer allows you to send emails from your application using mailer classes and views - Ruby on Rails 

Let's create an action that emails you everytime a new book is added to our database/store.

Create a Mailer

Run rails g mailer BookMailer

Output: image

Click on the domain. Similar to the screen below. The domain will be the sandbox url.

image

Add a verified user to test emails.

image

From the SMTP settings, find the following information:

image

Configure Our Mail Settings

In config/environments/development.rb, scroll to the bottom. Make sure to place it before the last "end"

Fill out the information from Mailgun SMTP settings.

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:              'smtp.mailgun.org',
  port:                 587,
  domain:               '<sandbox_something...>',
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true }

Example Config:

image

Add Method to Our Mailer

In app/mailers/application_mailer.rb:

class ApplicationMailer < ActionMailer::Base
  default from: 'aaron@coderacademy.edu.au'
  layout 'mailer'
end

Define the default email for the from address.

In app/mailers/book_mailer.rb:

class BookMailer < ApplicationMailer
  def new_book_email
    @user = params[:user]
    mail(to: @user.email, subject: 'A new book was added')
  end
end

Define the steps or actions taken when a new book is added.

Add a View

We will need to create a view page. The name of the view page will be based upon the method name in our mailer file. In this case, new_book_email.

For compatibility, we will create two files in app/views/book_mailer/:

  1. new_book_email.html.erb
  2. new_book_email.text.erb

We will paste the following sample code in each:

new_book_email.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>
      Thanks for adding **book**
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

new_book_email.text.erb

Thanks for adding a book!
===============================================
 
You have added **book**

Call the Method

In this case, we want to send an email WHEN a new book is created.

We navigate to the books_controller.rb file, and find the create method.

def create
    @author_exists = Author.all.find_by(name: params[:author])
    @author = @author_exists.nil? ? Author.create(name: params[:book][:author]) : @author_exists
    # binding.pry

    @book = Book.new(book_params)
    @book.author_id = @author.id
    @book.save

    redirect_to root_path
  end

We add the following lines to our original method:

def create
    @author_exists = Author.all.find_by(name: params[:author])
    @author = @author_exists.nil? ? Author.create(name: params[:book][:author]) : @author_exists
    # binding.pry

    @book = Book.new(book_params)
    @book.author_id = @author.id
    @book.save

    # New Book was created. Now send email alerting me. 
    @user = current_user
    BookMailer.with(user: @user).new_book_email.deliver_now
    redirect_to root_path
  end

Test Out Email Action

We navigate to http://localhost:3000/books/new and fill information for a book.

image

As soon as we hit 'Create Book', we can look at our console.

We should get the text version of our mailer view.

image

We should also, if we setup an authorized user email, get an actual email.

For example:

image

Checking Mailgun Dashboard

If we check the logs of our Mailgun account, we can confirm that the email went through.

image

Class Task

Create an .env file in the root directory of your rails application. Create variables using the syntax ENV['VARIABLE_NAME'] = .....

Take out the sensitive information from your config/environments/development.rb file, place it in variables within your .env file.

Then go back to your development.rb file and substitute the variables in.

Lastly, add the .env file to your .gitignore file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment