[Rails] Create an email sending function with ActionMailer (complete version)

Introduction

There was an implementation of the inquiry mail sending function for a certain matter. Personally, I will implement it myself for the first time, so as a memorandum, and since I could not implement it with just one article, I think that it will be useful for other people if I can complete the implementation just by looking at this article.

Implementation procedure

1. Create a model to use

#Set any model name and required columns
$ rails g model inquiry name:string text:string

$ rails db:migrate
2. Create Action Mailer

A class that inherits ApplicationMailer required to send an email can be created from the generate command.


$ rails g mailer inquiry
3. Settings for sending with Gmail

There are two things you need to do to be able to send emails from Rails. ① Password two-step verification setting ② Setting the app password ↑ can be set from here. After setting, please describe the following.

config/enviroments/development.rb



#If true, an error message will be displayed when the email is not sent
config.action_mailer.raise_delivery_errors = true

#Specifies whether fragment caching should be enabled in the mailer template
config.action_mailer.perform_caching = false

#Specify the delivery method
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
 address:              'smtp.gmail.com',
 port:                  587,
 domain:               'gmail.com',
 user_name:            '<gmail email address>',
 password:             'App password',
 authentication:       'plain',
 enable_starttls_auto:  true
}
4. Specify the email address and subject

app/mailer/inquiry_mailer.rb



def send_mail(inquiry)
  @inquiry = inquiry
  mail(
    from: '[email protected]', #Sender email address
    to:   '[email protected]',   #Destination email address
    subject: 'Inquiry email' #subject
  )
end

app/mailer/application_mailer.rb



class ApplicationMailer < ActionMailer::Base
  default from: '[email protected]'
  layout 'mailer'
end
5. Create the layout of the email body

To create the layout of the email body, create an erb file according to the naming convention. (app/views/mailer name_mailer/method name of mailer class.text.erb)

app/views/inquiry_mailer/send_mail.text.erb



==================================
<%= @inquiry.name %>I received an inquiry from Mr.
==================================

<Inquiry content>
<%= @inquiry.text %>
6. Check your email in preview

As for the class that inherits ActionMailer :: Preview, the InquiryMailerPreview class generated by the generate command exists, so write the following in it and check it.

spec/mailers/previews/inquiry_preview.rb



# Preview all emails at http://localhost:3000/rails/mailers/inquiry
class InquiryPreview < ActionMailer::Preview
  def inquiry
      inquiry = Inquiry.new(name: "Rennosuke Mihara", text: "Inquiry message")

      InquiryMailer.send_mail(inquiry)
  end

  private
  def inquiry_params
    params.require(:inquiry).permit(:name, :text)
  end
end

To check, start the server and connect to http: // localhost: 3000/rails/mailers/inquiry.

7. Actually send an email

Describe the process to be sent to the controller. That way, you'll get an email when you perform that action.

app/controllers/inquiries_controller.rb



class InquiriesController < ApplicationController

~ Omitted ~

  def create
    @inquiry = Inquiry.new(inquiry_params)

    if @inquiry.save
      #An email will be sent by executing this command
      InquiryMailer.send_mail(@inquiry).deliver
      redirect_to inquiries_path, flash: {success: 'Transmission is complete'}
    else
      flash.now[:alert] = 'Enter the required items, or there is an error in the entered contents'
      render :index
    end
  end

  private
  def inquiry_params
    params.require(:inquiry).permit(:name, :text)
  end
end

You can check it on the console ○


$ rails c

irb(main):001:0> inquiry = Inquiry.new(name: "Sample Taro", text: "Inquiry email")
irb(main):002:0> InquiryMailer.send_mail(inquiry).deliver_now

At the end

It's surprisingly easy to implement. It took me a while to realize that I personally set up Gmail, but I think that if you set it up properly, you will not stumble! I think it's a feature I use a lot, so let's implement it! !!

reference

[Introduction to Rails] Explaining Action Mailer email sending from the basics for beginners

[Rails] Email sending settings ~ Using gmail ~

Recommended Posts

[Rails] Create an email sending function with ActionMailer (complete version)
Create an EC site with Rails 5 ⑩ ~ Create an order function ~
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Implemented mail sending function with rails
Create pagination function with Rails Kaminari
[Rails withdrawal] Create a simple withdrawal function with rails
Create an or search function with Ransack.
Ruby on Rails Email automatic sending function implementation
Create an app by specifying the Rails version
Create an EC site with Rails5 ⑤ ~ Customer model ~
[Rails] Create an application
Create an EC site with Rails5 ⑦ ~ Address, Genre model ~
Create an EC site with Rails5 ④ ~ Header and footer ~
Create an EC site with Rails5 ⑥ ~ seed data input ~
Introduced graph function with rails
Ruby on Rails Email automatic sending function setting (using gmail)
Login function implementation with rails
Create an EC site with Rails5 ② ~ Bootstrap4 settings, Controller / action definition ~
Rails Tutorial Extension: I tried to create an RSS feed function
Create an immutable class with JAVA
Create an app with Spring Boot 2
[Grover] Generate PDF with Rails [2020 version]
Create an excel file with poi
Create an app with Spring Boot
Create My Page with Rails devise
Email sending function with Action Mailer at the time of new registration
Create a SPA with authentication function with Rails API mode + devise_token_auth + Vue.js 3 (Rails edition)
Create an EC site with Rails5 ③-Set model associations and other things-
Let's create an instance with .new yourself. .. ..
Create an infinite scroll with Infinite Scroll and kaminari
Send an email from gmail with Ruby
[Java] Create an executable module with Gradle
[Rails6] Create a new app with Rails [Beginner]
Create Rails 6 + MySQL environment with Docker compose
Make a login function with Rails anyway
[Rails 5] Create a new app with Rails [Beginner]
[Vue.js] Implementation of menu function Implementation version rails6
Let's make an error screen with Rails