1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでユーザー全員にメールを送る。

Posted at

初めに

ユーザー全員にメールを送る方法を書いていきます。

下準備

まずはアプリの設定から

rails new sample_mail
rails g model user name:string email:string
rails db:migrate
rails g controller mails index send_mail

としてroutes.rbに

get 'mails/index'
get 'mails/send_mail'

でOK

gemfileに

gem 'faker'

として

でもデータをつくっていく

rails c
100.times { User.create(name: Faker::Name.first_name, email: Faker::Internet.email }

これでユーザが100人つくれました。

メールを送る

まずは

rails g mailer SampleMailer

とする。

そうすると必要なファイルが作成される。

mailers/sample_mailer.rbにユーザにメールを送る処理を書いていく

sample_mailer.rb

def send_mail(user)
  @user = user
  mail(subject: '確認メール',to: user.email, from: "test@example.com")
end 

def self.send_mail_users
  @users = User.all
  @users.each do |user|
    SampleMailer.send_mail(user).deliver_now
  end 
end 

send_mailメソッドは普通に一つのユーザーにメールを送るもので

SampleMailer.send_mail(user).deliver_now

でuserにメールを送ることができます。

なのでself.send_mail_usersで@users = User.allをしてそこからループで@users全員にメールを送っています。

次に

views/sample_mailerのなかに送るメールの内容を書いていきます。

send_mail.html.erb,send_mail.text.erbを作ります。

ファイル名はメールを送るメソッドの名前と同じではいけないです。

適当に中身をかいたら完了です。

最後にメールに関する設定をconfig/environment/development.rbに書いていきます。

とりあえずは

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "127.0.0.1", port: 1025}

と書いておきます。

あとは実行してあげればメールを送れるので

views/mails/index.html.erbに

<%= link_to "送信", mails_send_mail_path %>

としてあげて

controllers/mails_controller.rbに


def index 
end 

def send_mail
  SampleMailer.send_mail_users
  redirect_to mails_index_path
end 

と書いてあげればOK

indexにアクセスして送信を押せば全員にメールを送れます。

確認

ちゃんとメールが送られているか確認したいので

gem install mailcatcher

として

コンソールで

mailcatcher

と打ってからメールを送信します。

そのあと

127.0.0.1:1080にアクセスしたら送ったメールを確認できます。

おわり:sunny:

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?