Rails send mail with GMail - ruby-on-rails

I am on rails 2.3.5 and have the latest Ruby installed and my application is running well, except, GMail emails.
I am trying to setup my gmail imap connection which has worked previously but now doesnt want to know.
This is my code:
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Gems
config.gem "capistrano-ext", :lib => "capistrano"
config.gem "configatron"
# Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
config.time_zone = "London"
# The internationalization framework can be changed to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')]
#config.i18n.default_locale = :de
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_base_session',
:secret => '7389ea9180b15f1495a5e73a69a893311f859ccff1ffd0fa2d7ea25fdf1fa324f280e6ba06e3e5ba612e71298d8fbe7f15fd7da2929c45a9c87fe226d2f77347'
}
config.active_record.observers = :user_observer
end
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%d/%m/%Y')
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%d/%m/%Y')
require "will_paginate"
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "XXXXXXXX.XXX",
:authentication => :plain,
:user_name => "XXXXXXXXXX.XXXXXXXXXX.XXX",
:password => "XXXXX"
}
But the above just results in an SMTP auth error in the production log.
I have read varied reports of this not working in Rails 2.2.2 but nothing for 2.3.5, anyone got any ideas?
Thanks,
Danny

Use action mailer optional tls

Related

Rails Application Very Slow To Start After Upgrade to Rails 5.1.3

I run a Rails 5.1.3 application on Pivotal Web Services. Since the upgrade from Rails 4 the application has the following behaviour:
deployment runs fine
puma starts
pivotal container is healthy
the first client that connects sits waiting for 2 to 3 minutes before being served the first page; during this period the server is using up to 100% CPU
This happens also when a new instance is being instantiated.
I have tried changing the 'eager loading' setting both true and false but no change in behaviour seen.
config.eager_load = true
I have tested with and without the rack-cors gem and also no changes.
Here is my config/application.rb:
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'pdfkit'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MyFaro
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Brussels'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
#config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :nl
#config.skylight.probes += %w(mongoid mongo)
config.middleware.use PDFKit::Middleware, {:print_media_type => true}, :only => %r[/print_story]
config.after_initialize do
ApplicationController.helpers.cache_set_look_up_hash
ApplicationController.helpers.cache_set_system_parameter_hash
end
end
end
and my config/environments/production.rb:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
#CORS
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.cache_store = :memory_store
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass

How to setup AWS credentials in rails for development?

I'm trying to figure out what is the best way to set up my credentials in development? I'm able to set up credentials in production because of heroku's configuration variables... but need help doing so if you're just testing app locally.
I have this in my development.rb
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['BUCKET_NAME'],
:access_key_id => ENV['ACCESS_KEY_ID'],
:secret_access_key => ENV['SECRET_ACCESS_KEY']
}
}
But, I'm not sure how to reference these ENV variables?
I created this aws.yml file in my /config folder
development:
BUCKET_NAME: "somename"
ACCESS_KEY_ID: "4205823951412980"
SECRET_ACCESS_KEY: "123141ABNCEFEHUDSL2309489850"
I thought if I matched the ENV name, it'll work? I guess thats not the case...
I made sure to include aws.yml to my .ignore file
/config/aws.yml
You are looking for dotenv gem. Install the gem gem 'dotenv-rails', :groups => [:development, :test], then
just create and `.env' file and put the variables into it like this.
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE
I like to use Foreman locally and store all my variables in a .ENV file. Plays well with Heroku and is easy to manage. Also in my case I have the following:
Under config/initiliazers/aws.rb
require 'aws-sdk'
require 'aws-sdk-resources'
# Rails.configuration.aws is used by AWS, Paperclip, and S3DirectUpload
Rails.configuration.aws = YAML.load(ERB.new(File.read("#{Rails.root}/config/aws.yml")).result)[Rails.env].symbolize_keys!
AWS.config(logger: Rails.logger)
AWS.config(Rails.configuration.aws)
Under config/initializers/paperclip.rb
# https://devcenter.heroku.com/articles/paperclip-s3
if Rails.env.test?
Paperclip::Attachment.default_options.merge!(
path: ":rails_root/public/paperclip/:rails_env/:class/:attachment/:id_partition/:filename",
storage: :filesystem
)
else
Paperclip::Attachment.default_options.merge!(
url: ':s3_domain_url',
path: '/:class/:filename',
storage: :s3,
s3_credentials: Rails.configuration.aws,
s3_protocol: 'https'
)
end
Under config/aws.yml
defaults: &defaults
access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
test:
<<: *defaults
bucket: <%= ENV['AWS_TEST_BUCKET'] %>
development:
<<: *defaults
bucket: <%= ENV['AWS_TEST_BUCKET'] %>
production:
<<: *defaults
bucket: <%= ENV['AWS_BUCKET'] %>
What I like to is create a config.yml on my ./config directory.
then I tell the ./config/application.rb I have a small block that loads the variables like
config.before_initialize do
dev = File.join(Rails.root, 'config', 'config.yml')
YAML.load(File.open(dev)).each do |key,value|
ENV[key.to_s] = value
end if File.exists?(dev)
end
Here is my ./config/config.yml
BUCKET_NAME: "somename"
ACCESS_KEY_ID: "4205823951412980"
SECRET_ACCESS_KEY: "123141ABNCEFEHUDSL2309489850"
New Updates
Here is a copy of my #config/application.rb
#config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Appname
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
initializer 'setup_asset_pipeline', :group => :all do |app|
# We don't want the default of everything that isn't js or css, because it pulls too many things in
app.config.assets.precompile.shift
# Explicitly register the extensions we are interested in compiling
app.config.assets.precompile.push(Proc.new do |path|
File.extname(path).in? [
'.html', '.erb', '.haml', # Templates
'.png', '.gif', '.jpg', '.jpeg', # Images
'.eot', '.otf', '.svc', '.woff', '.ttf', # Fonts
]
end)
end
I18n.enforce_available_locales = false
config.before_initialize do
dev = File.join(Rails.root, 'config', 'config.yml')
YAML.load(File.open(dev)).each do |key,value|
ENV[key.to_s] = value
end if File.exists?(dev)
end
end
end
If everything else fails, you can simply start your rails app with command line params. It is good to know the base case, where you know for sure that your params are indeed passed to your app:
ACCESS_KEY_ID=ABCDEFG SECRET_ACCESS_KEY=secreTaccessKey BUCKET_NAME=dev-images rails s
I actually prefer to set an alias in env:
alias railss='ACCESS_KEY_ID=ABCDEFG SECRET_ACCESS_KEY=secreTaccessKey BUCKET_NAME=dev-images rails s'

Rails 4.1 and exception_notification-rake gem causing uninitialized constant ExceptionNotification

I've upgraded to Rails 4.1 and am trying to set up the exception_notification-rake gem to notify me by email of failed rake tasks.
In my Gemfile, I have gem 'exception_notification-rake'.
In development.rb, I have the following:
MyApp::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.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
# Specify what domain to use for mailer URLs
config.action_mailer.default_url_options = {host: "localhost:3000"}
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:domain => 'gmail.com',
:user_name => Rails.application.secrets.email['user'],
:password => Rails.application.secrets.email['pass'],
:authentication => 'login',
:enable_starttls_auto => true
}
# 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
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
Bullet.bullet_logger = true
Bullet.console = true
# Bullet.growl = true
Bullet.rails_logger = true
Bullet.add_footer = true
end
config.middleware.use ExceptionNotification::Rack,
:ignore_if => lambda { |env, exception| !env[:rake?] },
:email => {
:sender_address => %{"notifier" myemail#gmail.com},
:exception_recipients => %w(myemail#gmail.com)
}
ExceptionNotifier::Rake.configure
end
As you can see, I'm passing in the user and password using Rails 4.1's secrets.yml file.
When I try starting up my Rails server, I get the following error:
/development.rb:52:in `
block in <top (required)>': uninitialized constant ExceptionNotification (NameError)
I'm guessing this is a bug in the exception_notification-rake gem which calls a previous version of the exception_notification, but I'm not sure. Any help with this would be appreciated!
Thanks :)
Update:
I've notified the exception_notification-rake gem developer about this. I have all the prerequisite gems and have a fairly vanilla setup so I think this might be a bug that needs to be fixed for Rails 4.1
As can be seen in this issue the current, published, version of ExceptionNotification does not work with rails 4.1
Until the new version is released, you can just use the master version. In your Gemfile include your gem as follows:
gem 'exception_notification', github: 'smartinez87/exception_notification'
The maintainer has released a rc-version, which you can use as follows
gem 'exception_notification', '4.1.0.rc1'
Once the new gem version is released, you can switch to the released version (4.1.0). This should not take too long I guess ;)

ROR send email heroku, gmail

I managed to configure ActionMailer on my local machine to send emails via Gmail. (it required tlsmail in gemfile)
### config/environment.rb
require 'tlsmail'
Ideas::Application.configure do
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'smtp.gmail.com',
:port => '587',
:domain => 'xxxx#gmail.com',
:user_name => 'xxxx#gmail.com',
:password => 'xxxxxxx',
:authentication => :plain
}
end
This worked on my local machine (the emails were sent) but as usually hreoku had some problems with this (Errno::ECONNREFUSED (Connection refused - connect(2))). I googled that they have a particular solution for gmail:
http://blog.heroku.com/archives/2009/11/9/tech_sending_email_with_gmail/
They are saying I need an additional SMTP TLS library. As mentioned above I added a gem that resolved the issue but only on my local machine. Well ok, I tried their solution and it worked... on heroku, but stopped working on my local. (it doesn't give an error, it just says the email was sent, but it never is.)
Environmental variables are set properly.
Do you have any ideas how to make at least one of this methods work both on my local machine and heroku?
Bye
You need to set it up in the correct environment. You'll need to do this in your gemfile with groups
group :development do
gem '<development gem here>'
group :production do
gem '<production gem here>'
Don't forget to rebundle. Then move the config relevant to each environment into either config/environments/production.rb or config/environments.development.rb

Geokit in Ruby on Rails, problem with acts_as_mappable

i have looked through the list of related questions however my problem does not seem to be listed and hence here it is:
Basically I'm trying to use Geokit within the Ruby on Rails environment, im not sure if i installed it properly, I have included it within the environment.rb (and done rake db:install) and i'm now trying to do the following:
require 'active_record'
require 'geokit'
class Store < ActiveRecord::Base
acts_as_mappable
end
Unforunately, when i try to run this and see if its ok, i get the following error:
c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.4/lib/active_record/base.rb:1959:in `method_missing': undefined local variable or method `acts_as_mappable' for #<Class:0x4cd261c> (NameError)
from C:/Users/Erika/Documents/Visual Studio 2008/Projects/StoreLocator/StoreLocator/app/models/store.rb:5
I am running Ruby in Steel for Visual Studio 2008, i'm not sure what i'm doing wrong as all the online tutorials i find tend to be rather old and done apply to me. Any help would be greatly appreciated. thanks!
Edit: (adding as per Ben's Request)
The following is what my environment.rb looks like
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "geokit"
config.gem "ym4r"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
# These defaults are used in GeoKit::Mappable.distance_to and in acts_as_mappable
GeoKit::default_units = :kms
GeoKit::default_formula = :sphere
# This is the timeout value in seconds to be used for calls to the geocoder web
# services. For no timeout at all, comment out the setting. The timeout unit
# is in seconds.
#GeoKit::Geocoders::timeout = 3
# These settings are used if web service calls must be routed through a proxy.
# These setting can be nil if not needed, otherwise, addr and port must be
# filled in at a minimum. If the proxy requires authentication, the username
# and password can be provided as well.
GeoKit::Geocoders::proxy_addr = nil
GeoKit::Geocoders::proxy_port = nil
GeoKit::Geocoders::proxy_user = nil
GeoKit::Geocoders::proxy_pass = nil
# This is your yahoo application key for the Yahoo Geocoder.
GeoKit::Geocoders::yahoo = 'REPLACE_WITH_YOUR_YAHOO_KEY'
# This is your Google Maps geocoder key.
GeoKit::Geocoders::google = 'apikey'
# This is your username and password for geocoder.us.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, the value should be set to username:password.
GeoKit::Geocoders::geocoder_us = false
# This is your authorization key for geocoder.ca.
# To use the free service, the value can be set to nil or false. For
# usage tied to an account, set the value to the key obtained from
# Geocoder.ca.
GeoKit::Geocoders::geocoder_ca = false
# This is the order in which the geocoders are called in a failover scenario
# If you only want to use a single geocoder, put a single symbol in the array.
# Valid symbols are :google, :yahoo, :us, and :ca.
# Be aware that there are Terms of Use restrictions on how you can use the
# various geocoders. Make sure you read up on relevant Terms of Use for each
# geocoder you are going to use.
GeoKit::Geocoders::provider_order = [:google]
acts_as_mappable is part of geokit-rails. You need to install the geokit-rails plugin.
script/plugin install git://github.com/andre/geokit-rails.git
To check if the plugin is properly installed, look under the vendor/plugins directory of your Rails app. It should have a geokit-rails sub directory. It it, you'll find all the plugin files, other subdirectories, including the file acts_as_mappable.rb (in vendor\plugins\geokit-rails\lib\geokit-rails).
If everything seems to be properly installed, try adding "require geokit" to the top of the init.rb file in the plugin root folder (vendor\plugins\geokit-rails).
Be sure to restart your app server after making the modifications.
What method are you using to include the geokit library? The plugin? The gem? Is the gem unpacked into vendor? What does your environment.rb look like?
Edit: I meant to leave this as a comment on the question - pardon me.

Resources