Ben Smith
Ben Smith

Reputation: 819

Ruby on Rails: Send Email when Creating a Record Doesn't Work

I'm wondering if someone could help me, within my Ruby on Rails application I am trying to get the system to send an email from a specific email address (Gmail) to a specific email address (Gmail), but for some reason the email does not send - but there is no error message.

Within my controller I have the following code to send an email when a new record is saved:

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

This should call this Mailer:

class UserMailer < ApplicationMailer
  default from: '[email protected]'

  def welcome_email()
     mail(to: '[email protected]', subject: 'Welcome to My Awesome Site')
  end
end

My Application Mailer is as follows:

class ApplicationMailer < ActionMailer::Base
  default from: "[email protected]"
  layout 'mailer'
end

I then have the 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>

And a similar text version of the above.

For some reason this isn't working, I have the following in $RAILS_ENV (in \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: '[email protected]'}

The the below in development.rb of the same location:

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:            '[email protected]', #replace with your username Eg. john.smith
    password:             'mypassword', #replace with your gmail password
    authentication:       'plain',
    enable_starttls_auto: true  }
end

And the below in production.rb in the same location:

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

And my Gemfile is as follows:

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

What I get in the log when creating a new record is as follows:

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 [email protected] (442.0ms)
Date: Wed, 08 Jun 2016 19:41:11 +0100
From: [email protected]
To: [email protected]
Message-ID: <[email protected]>
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)

I am really confused as to why this isn't working, does anybody know?

Please note that I am using Windows 7 and running Rails 4.2.6.

Upvotes: 0

Views: 1454

Answers (2)

Bijendra
Bijendra

Reputation: 10015

Mails are not delivered by default in development environment, Add this

      `config.action_mailer.perform_deliveries = true`

in your development.rb to perform deliveries. if you are using Rails 4, use

 Notifier.welcome(User.first).deliver_now

As per the documentation, you can also use

 Notifier.welcome(User.first).deliver_now!  

which Delivers an email without checking perform_deliveries and raise_delivery_errors, so use with caution.

Edit:

I see domain missing from your mailer setting in production.rb, use

 :domain               => "gmail.com",

Upvotes: 0

Sourabh Ukkalgaonkar
Sourabh Ukkalgaonkar

Reputation: 156

I think you need to use deliver_now instead of deliver.

UserMailer.welcome_email.deliver_now

Hope this will work for you.

Upvotes: 1

Related Questions