[Ruby] When sending a new registration, Action Mailer will send an email.

1 minute read

Overview

Use Action Mailer to send a welcome email when you register.

Premise

Implementation of login function using devise.

Introduction procedure

1. Setting to use Action Mailer

The description method uses Gmail as the sender of the welcome email. Describe the setting method of Action Mailer in config/environments/development.rb.

development.rb


Rails.application.configure do

#---Omitted---#

Config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    port: 587,
    address:'smtp.gmail.com',
    domain:'gmail.com',
    user_name:'source address',
    password:'App password',
    authentication: :plain,
    enable_starttls_auto: true
  }

For the application password, set the two-step authentication and issue the upper 16-digit password and enter it in the application password. The following is for reference only. ・[Get password for Google Mail application] (https://qiita.com/miriwo/items/833d4189140831c5d039) ・[How to turn on Google 2-step verification setting] (https://qiita.com/miriwo/items/0331e7241710fb4759fe)

2. Create Mailer class

$ rails g mailer UserNotice

3. Edit Mailer class

app/mailers/user_notice_mailer.rb


class UserNoticeMailer <ApplicationMailer
  def send_signup_email(user)
    @user = user
    mail to: @user.email, subject: "Member registration completed."
  end
end

4. Create email body

app/views/user_notice_mailer/send_signup_email.text.erb


Welcome <%= @user.name %>

Thank you for registering your account.

5. User model edit

app/models/user.rb


#---add to---#

  after_create :send_welcome_mail
 
  def send_welcome_mail
    UserNoticeMailer.send_signup_email(self).deliver
  end

By using after_create, you can call the method to send an email after a new User is created.

You should now receive a welcome email.