Ruby on Rails: отправка электронной почты при создании записи не работает

Мне интересно, может ли кто-нибудь помочь мне, в моем приложении Ruby on Rails я пытаюсь заставить систему отправлять электронную почту с определенного адреса электронной почты (Gmail) на определенный адрес электронной почты (Gmail), но по какой-то причине электронная почта не отправляет - но сообщения об ошибке нет.

В моем контроллере у меня есть следующий код для отправки электронного письма при сохранении новой записи:

def create
    @email = Email.new(email_params)
    if @email.save
   UserMailer.welcome_email.deliver
        redirect_to @email
    else
        render 'new'
    end
end

Это должно назвать это Mailer:

class UserMailer < ApplicationMailer
  default from: 'abc@123.com'

  def welcome_email()
     mail(to: '123@abc.com', subject: 'Welcome to My Awesome Site')
  end
end

Мое приложение Mailer выглядит следующим образом:

class ApplicationMailer < ActionMailer::Base
  default from: "abc@123.com"
  layout 'mailer'
end

Тогда у меня есть welcome_email.html.erb:

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to Thor Cinemas,!</h1>
     <p>
      You have successfully signed up to Thor Cinemas,
      your username is: .<br>
    </p>
    <p>
      To login to the site, just follow this link: <%= @url %>.
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

И похожая текстовая версия выше.

По какой-то причине это не работает, у меня есть следующее в $RAILS_ENV\config\environments):

config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'abc@123.com'}

Ниже в development.rb того же места:

Rails.application.configure do
  config.cache_classes = false
  config.eager_load = false
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.raise_delivery_errors = false
  config.active_support.deprecation = :log
  config.active_record.migration_error = :page_load
  config.assets.debug = true
  config.assets.digest = true    
  config.assets.raise_runtime_errors = true      
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'example.com',
    user_name:            '123@abc.com', #replace with your username Eg. john.smith
    password:             'mypassword', #replace with your gmail password
    authentication:       'plain',
    enable_starttls_auto: true  }
end

И ниже в production.rb в том же месте:

Rails.application.configure do
  config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
  config.assets.js_compressor = :uglifier
  config.assets.compile = false
  config.assets.digest = true
  config.log_level = :debug
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
  config.log_formatter = ::Logger::Formatter.new
  config.active_record.dump_schema_after_migration = false
  config.action_mailer.delivery_method = :smtp
    config.action_mailer.smtp_settings = {
     :address              => "smtp.gmail.com",
     :port                 => 587,
     :user_name            => ENV['EMAIL_USER'],
     :password             => ENV['EMAIL_PASSWORD'],
     :authentication       => "plain",
    :enable_starttls_auto => true
    }
end

И мой Gemfile как следует:

source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.6'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more:         https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
end

group :development do
 # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'validates_email_format_of'
gem "letter_opener", :group => :development

Что я получаю в log при создании новой записи происходит следующее:

Started POST "/emails" for ::1 at 2016-06-08 19:41:10 +0100
Processing by EmailsController#create as HTML
  Parameters: {"utf8"=>"✓",     "authenticity_token"=>"5MZ3NNxbc5T5T/S9vLFK7EskqEGg4Xd2ZBimoQd3eXklW9HW+i+wxRryp    CFg//I5UUq7SnesIfPR0LDM4VFy7w==", "email"=>{"title"=>"qqqqqqqqqqqqqqqqq",     "text"=>""}, "commit"=>"Create Email"}
  [1m[36m (0.0ms)[0m  [1mbegin transaction[0m
  [1m[35mSQL (1.0ms)[0m  INSERT INTO "emails" ("title", "text", "created_at",     "updated_at") VALUES (?, ?, ?, ?)  [["title", "qqqqqqqqqqqqqqqqq"], ["text",     ""], ["created_at", "2016-06-08 18:41:10.647620"], ["updated_at", "2016-06-08     18:41:10.647620"]]
  [1m[36m (173.0ms)[0m  [1mcommit transaction[0m
  Rendered user_mailer/welcome_email.html.erb within layouts/mailer (0.0ms)
  Rendered user_mailer/welcome_email.text.erb within layouts/mailer (0.0ms)

UserMailer#welcome_email: processed outbound mail in 264.0ms

Sent mail to 123@abc.com (442.0ms)
Date: Wed, 08 Jun 2016 19:41:11 +0100
From: abc@123.com
To: 123@abc.com
Message-ID: <575866c716216_1fa44e42ca8808bd@mylaptop.mail>
Subject: Welcome to My Awesome Site
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_575866c714aa5_1fa44e42ca880795";
 charset=UTF-8
Content-Transfer-Encoding: 7bit


----==_mimepart_575866c714aa5_1fa44e42ca880795
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

Welcome to example.com, 
===============================================

You have successfully signed up to example.com,
your username is:.

To login to the site, just follow this link: http://localhost:3000/email/new.

Thanks for joining and have a great day!

----==_mimepart_575866c714aa5_1fa44e42ca880795
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<html>
  <body>
    <!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome!</h1>
    <p>    
    </p>
    <p>
      To login to the site, just follow this link:     http://localhost:3000/email/new.
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>
  </body>
</html>

----==_mimepart_575866c714aa5_1fa44e42ca880795--

Redirected to http://localhost:3000/emails/42
Completed 302 Found in 890ms (ActiveRecord: 174.0ms)


Started GET "/emails/42" for ::1 at 2016-06-08 19:41:11 +0100
Processing by EmailsController#show as HTML
  Parameters: {"id"=>"42"}
  [1m[35mEmail Load (0.0ms)[0m  SELECT  "emails".* FROM "emails" WHERE     "emails"."id" = ? LIMIT 1  [["id", 42]]
  Rendered emails/show.html.erb within layouts/application (0.0ms)
Completed 200 OK in 86ms (Views: 84.1ms | ActiveRecord: 0.0ms)


Started GET "/emails" for ::1 at 2016-06-08 19:41:13 +0100
Processing by EmailsController#index as HTML
  [1m[36mEmail Load (0.0ms)[0m  [1mSELECT "emails".* FROM "emails"[0m
  Rendered emails/index.html.erb within layouts/application (9.0ms)
Completed 200 OK in 88ms (Views: 87.3ms | ActiveRecord: 0.0ms)

Я действительно смущен, почему это не работает, кто-нибудь знает?

Обратите внимание, что я использую Windows 7 и использую Rails 4.2.6.

2 ответа

Я думаю, что вам нужно использовать Delivery_now вместо Delivery.

UserMailer.welcome_email.deliver_now

Надеюсь, это сработает для вас.

Почта не доставляется по умолчанию в среде разработки, Добавить это

      `config.action_mailer.perform_deliveries = true`

в вашем development.rb выполнять доставки. если вы используете Rails 4, используйте

 Notifier.welcome(User.first).deliver_now

Согласно документации, вы также можете использовать

 Notifier.welcome(User.first).deliver_now!  

который доставляет электронное письмо, не проверяя execute_deliveries и rise_delivery_errors, поэтому используйте его с осторожностью.

Редактировать:

Я вижу, что домен отсутствует в настройках вашего почтовика в production.rb, используйте

 :domain               => "gmail.com",
Другие вопросы по тегам