質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

Q&A

解決済

4回答

7079閲覧

ActionMailerの使い方が知りたいです。

miyuki651020

総合スコア13

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails 4

Ruby on Rails4はRubyによって書かれたオープンソースのウェブフレームワークです。 Ruby on Railsは「設定より規約」の原則に従っており、効率的に作業を行うために再開発を行う必要をなくしてくれます。

0グッド

3クリップ

投稿2017/03/12 08:42

編集2017/03/14 02:16

###RailsのAction Mailerで、送信ボタンを押すと同時に、管理者側と返信先にメールが届く機能の実装。

HTMLで作ったものをRailsに反映させる方法で、自分のホームページを作っています。お問い合わせフォームで、手も足も出ない状況になりました。

###発生している問題・「メールが宛先に届かなかった。」

app/mailer/contact_mailer.rb

class ContactMailer < ApplicationMailer::Base default from: "#自分のメアド", reply_to: "<%= @contact.email %>", cc: "#自分のメアド", charset: 'UTF-8' def received_email(arg) @arg = arg @greeting = "Hi" mail (to: "<%= @contact.email %>", cc: "#自分のメアド", subject: 'ご連絡、ありがとうございます。') end end

app/views/contact_mailer/received_email.text.rb

webサイトから問い合わせがありました。 -------------------------- Name:<br> <%= @contact.name %> Email:<br> <%= @contact.email %> Text:<br> <%= @contact.text %> --------------------------

app/models/contact.rb

class Contact include ActiveModel::Model attr_accessor :name, :email, :text #これ大事 validates :name, :length => { minimum: 3, :too_short => 'お名前(ニックネームも可)を入力してください。'} validates :email, :length => { minimum: 3, :too_short => 'メールアドレスを入力してください。'} validates :text, :presence => {:message => 'メッセージを入力してください。'} end

app/views/contact/index.html.erb

<%= form_for @contact, :url => contact_create_path do |f| %> <% if @contact.errors.any? %> <div class="alert alert-danger" role="alert"> <strong>入力内容にエラーがあります</strong> <ul> <% @contact.errors.each do |attr, msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <h3>メッセージを送る</h3> <table class="table"> <tr> <td><%= f.text_field :name, placeholder: 'お名前(必須)', class: 'name' %></td> </tr> <tr> <td><%= f.text_field :email, placeholder: 'メールアドレス(必須)', class: 'email' %></td> </tr> <tr> <td><%= f.text_area :text, placeholder: 'よかったら、メッセージをお願いします!', rows: '10', class: 'text' %></td> </tr> </table> <div class="submit"> <%= f.submit 'SENT', class: 'submit-button' %> </div> <% end %>

app/controllers/contact_controller.rb

class ContactController < ApplicationController def index @contact = Contact.new render :action => 'index' end def create @contact = Contact.new(contact_params) end def sendmail @mail = ContactMailer.received_email(@contact).deliver render text: 'メール送信完了' render :action => 'create' end private def contact_params params.require(:contact).permit(:name, :email, :text) end end

confing/routes.rb

Rails.application.routes.draw do root "top#index" get "top" => "top#index" get "top/profile" => "top#profile" get "top/cost" => "top#cost" get "contact" => "contact#index" post "contact/create" => "contact#create" end

confing/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com", :port => 587, :domain => 'gmail.com', :user_name => "#自分のgmailアドレス", :password => "#自分のgmailアドレスのパスワード", :authentication => 'plain' }

$ vi config/environments/development.rb

Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. # ActionMailer config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.web_console.whitelisted_ips = '0.0.0.0/0' config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :letter_opener_web config.action_mailer.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com", :port => 587, :domain => 'gmail.com', :user_name => "", #自分のgmailアドレス :password => "", #自分のgmailアドレスのパスワード :authentication => 'plain' } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end

app/views/contact/create.html.erb

<div class="contents"> <div class="success"> <h3>投稿が完了しました。</h3> <a class="btn" href="/top">一覧へ戻る</a> </div> </div>

###試したこと
dbと関係ない[Rails 4.1] ActiveModelを使って、DBと関係ないFormを作り、確認画面付きのお問い合わせフォームを作る方法
メール送信の方法 (Rails4/ActionMailer)
を参考にしました。

メール送信画面
送信完了画面

画像のように、ビューは動くのですが、肝心のメールが送信できませんでした。
どなたかお詳しい方、お教え願えませんでしょうか。

よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ryochin

2017/03/13 02:09

実行時に log/development.log にエラーらしき行はありませんでしたか?
miyuki651020

2017/03/13 08:46

Started GET "/" for ::1 at 2017-03-08 16:28:10 +0900 Processing by Rails::WelcomeController#index as HTML Rendered /Users/131miyuki/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/templates/rails/welcome/index.html.erb (3.7ms) Completed 200 OK in 34ms (Views: 20.5ms | ActiveRecord: 0.0ms)となってます。
miyuki651020

2017/03/13 09:04

# Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. # ActionMailer config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.web_console.whitelisted_ips = '0.0.0.0/0' config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :letter_opener_web config.action_mailer.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmail.com",:port => 587, :domain => 'gmail.com',:user_name => "gmailアドレス",:password =>"", :authentication => 'plain' } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true endと出てます。($vi config/environments/development.rb)
guest

回答4

0

Started GET "/contact" for ::1 at 2017-03-14 16:44:25 +0900
Processing by ContactController#index as HTML
Rendered contact/index.html.erb within layouts/application (1.3ms)
Completed 200 OK in 41ms (Views: 40.6ms | ActiveRecord: 0.0ms)

Started POST "/contact/create" for ::1 at 2017-03-14 16:45:24 +0900
Processing by ContactController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"64xiWZD5/FTPFNRuqINeQ00sAtsPt+MSyzzJo4URU4M8WeLHYeS/T7tV+nf3cbTfjw5MRcGjHe0A/QW6irxFYQ==", "contact"=>{"name"=>"届いていますか?", "email"=>"hogehogehogehoge@example.com", "text"=>"届いてますか???????\r\nこんにちは!!!!!!!!!!!!\r\n"}, "commit"=>"SENT"}
DEPRECATION WARNING: #deliver is deprecated and will be removed in Rails 5. Use #deliver_now to deliver immediately or #deliver_later to deliver through Active Job. (called from create at /Users/131miyuki/projects/MIYUKImémoires/app/controllers/contact_controller.rb:10)
Rendered contact_mailer/received_email.html.erb (0.9ms)
Rendered contact_mailer/received_email.text.erb (0.4ms)

ContactMailer#received_email: processed outbound mail in 41.7ms

Sent mail to example@example.com (25.3ms)
Date: Tue, 14 Mar 2017 16:45:24 +0900
From: example@example.com
Reply-To: reply_to@example.com
To: example@example.com
Cc: miyuki.651020@gmail.com
Message-ID: 58c79f9479270_556d3fdd114f64dc55776@MiyukinoMacBook-Air.local.mail
Subject: =?UTF-8?Q?web=E3=81=8B=E3=82=89=E3=81=8A=E5=95=8F=E3=81=84=E5=90=88=E3=82=8F=E3=81=9B=E3=81=8C=E3=81=82=E3=82=8A=E3=81=BE=E3=81=97=E3=81=9F=E3=80=82?=
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="--==_mimepart_58c79f9478128_556d3fdd114f64dc5567";
charset=UTF-8
Content-Transfer-Encoding: 7bit

----==_mimepart_58c79f9478128_556d3fdd114f64dc5567
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: base64

d2Vi44K144Kk44OI44GL44KJ5ZWP44GE5ZCI44KP44Gb44GM44GC44KK44G+
44GX44Gf44CCCgotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQoKTmFtZTo8
YnI+CuWxiuOBhOOBpuOBhOOBvuOBmeOBi++8nwpFbWFpbDo8YnI+CmhvZ2Vo
b2dlaG9nZWhvZ2VAZXhhbXBsZS5jb20KVGV4dDo8YnI+CuWxiuOBhOOBpuOB
vuOBmeOBi++8n++8n++8n++8n++8n++8n++8nwrjgZPjgpPjgavjgaHjga/v
vIHvvIHvvIHvvIHvvIHvvIHvvIHvvIHvvIHvvIHvvIHvvIEKCi0tLS0tLS0t
LS0tLS0tLS0tLS0tLS0tLS0tCg==

----==_mimepart_58c79f9478128_556d3fdd114f64dc5567
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: base64

LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS08YnI+CgpOYW1lOjxicj4K5bGK
44GE44Gm44GE44G+44GZ44GL77yfPGJyPgpFbWFpbDo8YnI+CmhvZ2Vob2dl
aG9nZWhvZ2VAZXhhbXBsZS5jb208YnI+ClRleHQ6PGJyPgrlsYrjgYTjgabj
gb7jgZnjgYvvvJ/vvJ/vvJ/vvJ/vvJ/vvJ/vvJ8K44GT44KT44Gr44Gh44Gv
77yB77yB77yB77yB77yB77yB77yB77yB77yB77yB77yB77yBCjxicj4KLS0t
LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0KCgo8aDI+44OG44K544OIPC9oMj4K
PHA+44GC44GE44GG44GI44GK44GL44GN44GP44GR44GT44GV44GX44GZ44Gb
44Gd44Gf44Gh44Gk44Gm44Go44Gq44Gr44Gs44Gt44Gu44GC44GE44GG44GI
44GK44GL44GN44GP44GR44GT44GV44GX44GZ44Gb44Gd44Gf44Gh44Gk44Gm
44Go44Gq44Gr44Gs44Gt44Gu44GC44GE44GG44GI44GK44GL44GN44GP44GR
44GT44GV44GX44GZ44Gb44Gd44Gf44Gh44Gk44Gm44Go44Gq44Gr44Gs44Gt
44Gu44GC44GE44GG44GI44GK44GL44GN44GP44GR44GT44GV44GX44GZ44Gb
44Gd44Gf44Gh44Gk44Gm44Go44Gq44Gr44Gs44Gt44Gu44GC44GE44GG44GI
44GK44GL44GN44GP44GR44GT44GV44GX44GZ44Gb44Gd44Gf44Gh44Gk44Gm
44Go44Gq44Gr44Gs44Gt44Gu44GC44GE44GG44GI44GK44GL44GN44GP44GR
44GT44GV44GX44GZ44Gb44Gd44Gf44Gh44Gk44Gm44Go44Gq44Gr44Gs44Gt
44GuPC9wPgo=

----==_mimepart_58c79f9478128_556d3fdd114f64dc5567--

Rendered contact/create.html.erb within layouts/application (0.1ms)
Completed 200 OK in 120ms (Views: 48.3ms | ActiveRecord: 0.0ms)

Started GET "/letter_opener/" for ::1 at 2017-03-14 16:45:28 +0900
Processing by LetterOpenerWeb::LettersController#index as HTML
Rendered vendor/bundler/ruby/2.3.0/gems/letter_opener_web-1.3.1/app/views/letter_opener_web/letters/index.html.erb within layouts/letter_opener_web/application (4.2ms)
Completed 200 OK in 81ms (Views: 80.3ms | ActiveRecord: 0.0ms)

Started GET "/letter_opener/1489477524_a9193a1/rich" for ::1 at 2017-03-14 16:45:28 +0900
Processing by LetterOpenerWeb::LettersController#show as HTML
Parameters: {"id"=>"1489477524_a9193a1", "style"=>"rich"}
Rendered html template (0.0ms)
Completed 200 OK in 14ms (Views: 0.4ms | ActiveRecord: 0.0ms)

投稿2017/03/14 08:03

miyuki651020

総合スコア13

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

lapi

2017/03/14 13:06

無事にできたみたいで何よりです。 頑張ってください!
guest

0

教えてくださった皆様

miyuki651020です。

ついに、出来ました!

def create @contact = Contact.new(contact_params) @mail = ContactMailer. received_email(@contact).deliver else render :action => 'create' end end

胸がすきました!

ありがとう、本当にありがとうございます!!!!!

letter_opener_web

一つだけ質問があります。

example@example.comの部分は、なんでもいいのですか?

投稿2017/03/14 07:55

編集2017/03/14 08:31
miyuki651020

総合スコア13

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2017/03/14 08:27

おめでとうございます! toはexample@example.com以外も指定できます。 むしろこのままだとexample@example.com宛にメールが送信されているので問題かと。 例えば、toにはフォーム入力したユーザーさんのメールアドレスを指定して、 ccに管理者のメールアドレスを指定するとか。 フォーム入力したユーザーさんにメール送信する必要ない場合は、 toに管理者のメールアドレスを指定して、ccを使用しないとか。
miyuki651020

2017/03/14 08:57

えっと、例えば ``` mail(to: "<%= @contact.email %>", cc: "自分@gmail.com", subject: "webからお問い合わせがありました。") end ``` とかですか?
miyuki651020

2017/03/14 09:03

あ、"<%= %>"いらないですね。出来ました。
guest

0

そもそも、ContactControllerのsendmailがどこからも呼ばれてないからではないでしょうか?

投稿2017/03/14 03:37

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

0

ベストアンサー

現在開発しているのはローカル開発環境でしょうか?
developmentに設定しているのでローカルだということで話をすると、ローカル開発環境では、実際にメールを送信して確認することは非常に手間です。

なのでletter_opener_webというgemを利用すると便利です。

ビューは動くのですが、肝心のメールが送信できませんでした。

とのとこですが、ログは確認されていますか?
ログを確認して送信されていないのか、何かエラーが出ていないか確認してみると現在起こっている問題の原因がわかる場合もあります。

メールが送信されないとのことなので、考えられるのは
設定している内容が間違っている。
お問い合わせされた時にMailerが正しく呼び出されていない。
この辺が怪しいんではないのかと思います。

投稿2017/03/13 02:51

lapi

総合スコア58

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

miyuki651020

2017/03/13 08:38

ログは、started・・・completed 200 ok (・・・)みたいな、いけてそうなんですよね。逆にスムーズにいき過ぎみたいな。白紙のまま送信完了できるんですよ。エラー出る設定してるのに。なんか、画面だけ動いてる感じです! letter_opener_webは白紙のままで、送れなかったですね。何かが間違えてるんでしょうね。
miyuki651020

2017/03/13 09:07

ログって$vi config/environments/development.rbと打ちますか?
lapi

2017/03/13 14:13 編集

ローカル環境であれば ``rails s`` でサーバー立ち上げてログは見れます。 Herokuであれば ``heroku logs -t`` nginxアクセスログ ``cat /var/log/nginx/アプリ名_access.log;`` Unicornログ ``cat /var/www/アプリ名/shared/log/unicorn.log;`` 上記のように環境ごとにログの確認方法は異なりますが、このような感じでログは確認できます。 正常にメーラーが作動しメールが送信されると以下のようにログでは表示されます。 ``` NoticeMailer#sendmail_contact: processed outbound mail in 155.9ms Sent mail to aa@gmail.com (32.7ms) Date: Mon, 13 Mar 2017 23:01:16 +0900 From: from@example.com To: aa@gmail.com Message-ID: <58c6a62c93da4_703d3fc10819db48892c@MacBook-Pro.mail> Subject: =?UTF-8?Q?=E3=81=8A=E5=95=8F=E3=81=84=E5=90=88=E3=82=8F=E3=81=9B=E3=81=8C=E5=AE=8C=E4=BA=86=E3=81=97=E3=81=BE=E3=81=97=E3=81=9F?= Mime-Version: 1.0 Content-Type: multipart/alternative; boundary="--==_mimepart_58c6a62c915e9_703d3fc10819db4888cf"; charset=UTF-8 Content-Transfer-Encoding: 7bit ```
miyuki651020

2017/03/14 02:10

あ、rails sです!メール送信ボタン押したときのログは以下の通りです。 ``` Started GET "/contact" for ::1 at 2017-03-14 11:07:46 +0900 Processing by ContactController#index as HTML Rendered contact/index.html.erb within layouts/application (11.8ms) Completed 200 OK in 163ms (Views: 151.9ms | ActiveRecord: 0.0ms) Started POST "/contact/create" for ::1 at 2017-03-14 11:08:06 +0900 Processing by ContactController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"s4VphfA1Fp892JJaSEsGALCdDLk3L9wR8Mt76naHcIRkUOkbAShVhEmZvEMXueyccr9CJ/k7Iu47CrfzeSpmZg==", "contact"=>{"name"=>"", "email"=>"", "text"=>""}, "commit"=>"SENT"} Rendered contact/create.html.erb within layouts/application (0.2ms) Completed 200 OK in 65ms (Views: 63.5ms | ActiveRecord: 0.0ms) ```
miyuki651020

2017/03/14 02:38

どうやってメーラー呼び出せるのでしょうか。
lapi

2017/03/14 04:07

yasuhikomachinoさんがおっしゃるようにsendmailがどこからも呼ばれていないからだと僕も思います。 メーラーはコントローラーでアクションを呼び出す設定をします。 ログを見る限りではStarted POST "/contact/createでcreateアクションしか呼び出されていない状況です。 ですので、 def create @contact = Contact.new(contacts_params) if @contact.save redirect_to root_path, notice: "お問い合わせありがとうございました!" ContactMailer. received_email(@contact).deliver else render 'new' end end などにクリエイトアクションでメーラーを呼び出してあげるとどうでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問