Implemented mail sending function with rails

Introduction

<!-Description the beginning and outline-> Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field is used for input and is posted as output. The sample is a task management app. In this post, we will implement a function to send an email saying "○○ task has been registered" when the user registers the task.

table of contents

<!-Edit title and anchor name->

  1. Create Mailer
  2. Add Method (#Chapter2)
  3. Create Template
  4. Transmission processing implementation
  5. Operation check
  6. Create Test
  7. References

<!-Each chapter->

Creating a mailer

Mailer is ActionMailer, which is a function to send emails installed in rails. Just as the controller passes the information to the template and outputs the screen, the Mailer also passes the information to the template and sends an email. First, create the TaskMailer to be implemented this time. Execute the following command.

rails g mailer TaskMailer

Add method

The previous command will create a file called app/mailer/task_mailer.rb. Define the method "creation_email" of the email to be sent this time.

app/mailer/task_mailer.rb


def creation_email(task)
  @task = task
  mail(
    subject: 'Task creation completion email',
    to: '[email protected]',
    from: '[email protected]'
  )
end

When calling this method, ask the added task to be passed as an argument. Since the contents of task are displayed as a template, they are stored in instance variables.

Template creation

Next, create a template. Depending on the user's reception environment, it may not be possible to display html format emails. Create two types of files because the text format file is created together and sent together with the html format.

app/views/task_mailer/creation_email.html.slim


|I have created the following tasks

ul
  li
    |name:
    = @task.name
  li
    |detailed explanation
    = simple_format(@task.description)

app/views/task_mailer/creation_email.text.slim


|I have created the following tasks
= "\n"
|name:
= @task.name
= "\n"
|detailed explanation
= "\n"
= @task.description

Transmission processing implementation

At this point, all you have to do is describe the process to send! This time, in order to send an email together with the task save process, write the send process in the create method of tasks_controller.

app/controllers/tasks_controller.rb


Abbreviation
    if @task.save
      TaskMailer.creation_email(@task).deliver_now
      SampleJob.perform_later
      logger.debug "task:「#{@task.attributes.inspect}Was registered"
      redirect_to tasks_url, notice: "task"#{@task.name}Has been registered."
    else
      render :new
    end
Abbreviation

deliver_now is literally an immediate instruction. If you want to send an email in 5 minutes, use deliver_later (wait: 5 minutes).

Operation check

Was the email sent and is the content of the email as intended? To check this, we use a gem called "mailcatcher".

gem install mailcatcher

Execute the above command and write the following in the rails configuration file.

config/environments/development.rb


  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false
  #Add the following two lines
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = { address: '127.0.0.1', port: 1025}

The above is the setting of the development environment, but the setting of the production environment is described in procedure.rb.

After completing the description of the configuration file, restart the server. The confirmation procedure is

--Run mailcatcher in the terminal --Access http://127.0.0.1:1080/ after executing the mail sending flow

Then, you can check the sent mail.

Test creation

First, create a directory for mailer's Spec.

mkdir spec/mailers

Create task_mailer_spec.rb in the created folder and write as follows.

spec/mailers/task_mailer_spec.rb


require 'rails_helper'
describe TaskMailer, type: :mailer do
end

Now that the framework is complete, let's actually write the test.

spec/mailers/task_mailer_spec.rb


require "rails_helper"

RSpec.describe TaskMailer, type: :mailer do
  let(:task){FactoryBot.create(:task, name: 'Write Mailer Spec', description: 'Check the content of the email you sent')}
  let(:text_body) do
    part = mail.body.parts.detect{|part| part.content_type == 'text/plain; charset=UTF-8'}
    part.body.raw_source
  end
  let(:html_body) do
    part = mail.body.parts.detect{|part| part.content_type == 'text/html; charset=UTF-8'}
    part.body.raw_source
  end

  describe '#creation_email' do
    let(:mail){TaskMailer.creation_email(task)}

    it "The expected email is being generated" do
      expect(mail.subject).to eq('Task creation completion email')
      expect(mail.to).to eq(['[email protected]'])
      expect(mail.from).to eq(['[email protected]'])

      expect(text_body).to match('I have created the following tasks')
      expect(text_body).to match('Write Mailer Spec')
      expect(text_body).to match('Check the content of the email you sent')

      expect(html_body).to match('I have created the following tasks')
      expect(html_body).to match('Write Mailer Spec')
      expect(html_body).to match('Check the content of the email you sent')
    end
  end
end

Execute the following command and check if it passes.

bundle exec rspec spec/mailers/task_mailer_spec.rb

References

-Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field

Recommended Posts

Implemented mail sending function with rails
[Rails] Implemented hashtag function
Introduced graph function with rails
[Rails] (Supplement) Implemented follow function
Login function implementation with rails
Implemented authentication function with Spring Security ②
Implemented authentication function with Spring Security ③
[Rails] Create an email sending function with ActionMailer (complete version)
Create pagination function with Rails Kaminari
Implemented authentication function with Spring Security ①
[Rails withdrawal] Create a simple withdrawal function with rails
Make a login function with Rails anyway
Implemented follow function in Rails (Ajax communication)
[Rails 6] Asynchronous (Ajax) follow function is implemented
Fastest rails mail devise Welcome mail sending function implementation action mailer unnecessary Easyest
[Rails 6] Ranking function
[Rails] Category function
Rails follow function
Implemented comment function
[Rails] Notification function
Posting function implemented by asynchronous communication in Rails
Ruby on Rails Email automatic sending function implementation
Let's make a search function with Rails (ransack)
Create an EC site with Rails 5 ⑩ ~ Create an order function ~
[Rails, JavaScript] Implemented like function (synchronous / asynchronous communication)
[Rails] Implementation of drag and drop function (with effect)
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Rails deploy with Docker
[Rails 6] RuntimeError with $ rails s
[Rails] Implement search function
[For Rails beginners] Implemented multiple search function without Gem
Handle devise with Rails
[rails] tag ranking function
[Rails] Learning with Rails tutorial
Rails application guest login function implemented (devise not used)
[Rails] Test with RSpec
Rails search function implementation
[Rails] Development with MySQL
Supports multilingualization with Rails!
Double polymorphic with Rails
With Kotorin ―― 7. Scoping Function
Serverless Function with Micronaut
Ruby on Rails Email automatic sending function setting (using gmail)
[Ruby on Rails] Implement login function by add_token_to_users with API
Implement login function simply with name and password in Rails (3)
[Rails] Implemented a pull-down search function for Active Hash data
Implement application function in Rails
Rails fuzzy search function implementation
[Rails] Implement User search function
Search function using [rails] ransack
[Rails] Express polymorphic with graphql-ruby
Java to play with Function
Try using view_component with rails
[Vue Rails] "Hello Vue!" Displayed with Vue + Rails
Japaneseize using i18n with Rails
[Rails 6] Implementation of search function
API creation with Rails + GraphQL
Preparation for developing with Rails
Finally implemented Rails Form object
[Rails] Implementation of category function
Run Rails whenever with docker