ActionMailer isn't sending my email - ruby

I'm trying to use ActionMailer to automatically send a user an email. However, after save of the user, which should trigger the email. I don't see that any message has been sent to my inbox. The save took place without mistakes, but the mail never arrived. What is the problem?
mailers
class OrderNotifier < ActionMailer::Base
default from: "from#example.com"
def received(order)
#order = order
mail to: order, subject: 'Pragmatic Store Order Confirmation'
end
end
development.rb
Depot::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 = false
# 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.action_mailer.delivery_method = :sendmail
config.action_mailer.delivery_method = :test
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address:
"smtp.gmail.com",
port:
587,
domain:
"domain.of.sender.net",
authentication: "plain",
user_name:
"dave",
password:
"secret",
enable_starttls_auto: true
}
end
controller.rb
def create
#order = "a2010#mail.ru"
...
respond_to do |format|
if #user.save
OrderNotifier.received(#order).deliver
format.html { redirect_to #user}
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
...
end
view/order_notifier
Welcome to example.com
Thank you for your recent order from The Pragmatic Store.

you should only have one of those settings:
config.action_mailer.delivery_method = :sendmail
config.action_mailer.delivery_method = :test
config.action_mailer.delivery_method = :smtp
other than that always have the log/development.log file open and see what happens. rails will most likely tell you what it's about to do.
if you want to learn more about debugging, read this http://nofail.de/2013/10/debugging-rails-applications-in-development/

Related

How use sessions with Whats app cloud api?

Need to build chat bot with whatsapp, so i use Whats app cloud api + Sinatrarb.
When i need to send the session its sends perfectually, but its doesnt work
class WhatsAppSender < Sinatra::Base
configure :development do
register Sinatra::Reloader
enable :sessions
set :session_secret, "secret"
set :session_store, Rack::Session::Pool
end
configure do
enable :sessions
set :session_secret, "secret"
set :session_store, Rack::Session::Pool
end
post '/bot' do
request.body.rewind
body = JSON.parse request.body.read
# puts body
puts session[:answer]
if body['entry'][0]['changes'][0]['value'].include?("messages")
user_text = body['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
case
when user_text == "hi"
# puts session[:answer]
response = HTTP.auth("Bearer mytoken")
.headers(:accept => "application/json")
.post("https://graph.facebook.com/v14.0/myid/messages",
:json => { messaging_product: "whatsapp",
recipient_type: "individual",
to: "mynumber",
type: "text",
some_text: "some text",
text: { preview_url:
false,
body: "hi man"}
})
session[:answer] = "booking_amount"
puts response
when session[:answer] == "booking_amount"
puts "session works"
when user_text.downcase == "d"
session.clear
puts "cleared"
end
end
end
end
then i inspect request, sinatra session works fine, set the cookie
Set-Cookie rack.session=BAh7CEkiD3Nlc3Npb25faWQGOgZFVG86HVJhY2s6OlNlc3Npb246OlNlc3Npb25JZAY6D0BwdWJsaWNfaWRJIkViNThiYmJjMjdmYjI4MGU0ZTMxMDY4NzE4MDllOWVhYTBlNTVlM2UwMjg4ZWE3OWRiMjVmYTlkNThmZjczNzI3BjsARkkiCWNzcmYGOwBGSSIxbEJydTFnUm5tSTVCOVZUT1pZelNwSFY3a3ZUNGxiVmVHS2FlZVFvYVJsOD0GOwBGSSINdHJhY2tpbmcGOwBGewZJIhRIVFRQX1VTRVJfQUdFTlQGOwBUSSItNDJiNzI3MTFjNTdmZDA5YTk1MjY0NmY0N2Q0YWJjMjk0ODk5OTZhMQY7AEY%3D--f88a49537f00d65faf60da839b05d847d47f288d; path=/; HttpOnly
But its doesn't work... Maybe i should use another language or framework? please help.

Problems with implementing a realtime update with Rails5 and Actioncable

I'm trying to implement a simple rails fullstack todo app with action cable.
Unfortunately the docs on action cable is still confusing to me.
I tried to refer to DHH's example and https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable and adjusting to my app https://github.com/tenzan/rails-fullstack-todo
It's not showing realtime updates at http://localhost:3000/tasks when I used one browser for task creation and another one to see if it changes automatically.
My environment:
Mac OS X Sierra
Rails 5.0.0.1
Ruby 2.4.0
Redis enabled in Gemfile and running at port 6379
RethinkDB
I implemented:
app/assets/javascripts/channels/index.coffee
//= require cable
//= require_self
//= require_tree .
this.App = {};
App.cable = ActionCable.createConsumer();
app/assets/javascripts/channels/tasks.js
App.tasks = App.cable.subscriptions.create('TasksChannel', {
received: function(data) {
$("#tasks").removeClass('hidden')
return $('#tasks').append(this.renderTask(data));
}
});
app/channels/tasks_channel.rb
class TasksChannel < ApplicationCable::Channel
def subscribed
stream_from "tasks"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
app/controllers/tasks_controller.rb
def create
#task = Task.new(task_params)
respond_to do |format|
if #task.save
ActionCable.server.broadcast 'tasks', task: #task.title
format.html { redirect_to tasks_url, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: #task }
else
format.html { render :new }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
app/views/layouts/application.html.erb: Added <%= action_cable_meta_tag %>
config/cable.yml
local: &local
url: redis://localhost:6379
development: *local
test: *local
config/environments/development.rb
Rails.application.configure do
config.action_cable.url = "ws://localhost:3000/cable"
config/routes.rb
Rails.application.routes.draw do
mount ActionCable.server => '/cable'
app/views/tasks/index.html.erb
I suspect something wrong with
app/assets/javascripts/channels/tasks.coffee
app/views/tasks/index.html.erb
But I really don't have an idea how to fix/adjust them.

Sent emails with Action Mailer

I am trying to send an email to example#gmail.com with Action Mailer (Ruby on Rails). The method sendactivation is correctly executed and the message "Email sent" is displayed. However, I never receive any email. Actually, the output "Test" is never printed. My webapp is hosted on Heroku Cedar-10.
class UsersController < ApplicationController
def sendactivation
UserMailer.welcome_email()
render :json => {
:result => "Email sent"
}
end
end
end
class UserMailer < ActionMailer::Base
def welcome_email()
mail(to: "example#gmail.com",
body: "Hello",
content_type: "text/html",
subject: "Already rendered!")
puts "Test"
end
end
This is the configuration I have on my config/environment/production.rb. Actually I wanted to send it with Office 365 but I suppose it is easier to debug with a Gmail account.
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: 'example#gmail.com',
password: '########',
authentication: 'plain',
enable_starttls_auto: true }
What am I doing wrong? Is there anything I need to change on my Gmail configuration?
ANSWER: In addition to the marked answer, I needed to set the "from" address in the welcome_email method.
Call method deliver:
UserMailer.welcome_email.deliver
UserMailer.welcome_email.deliver_now
From the Rails Guide: See section 2.1.4
class SendWeeklySummary
  def run
    User.find_each do |user|
      UserMailer.weekly_summary(user).deliver_now
    end
  end
end

How to resolve Errno::ECONNREFUSED in UsersController#create error in ROR

Can anybody help me to resolve this following error.I am trying to send an email but it failed to send and throws some error.
Error:
Errno::ECONNREFUSED in UsersController#create
No connection could be made because the target machine actively refused it. - connect(2)
app/controllers/users_controller.rb:8:in `create'
My code snippets are given below.
views/users/index.html.erb
<h1>Send email to your friend</h1>
<%= form_for #user,:url => {:action => 'create'} do |f| %>
<%= f.text_field:name,placeholder:"Enter your name" %><br>
<%= f.email_field:email,placeholder:"Enter your email" %><br>
<%= f.submit "Send" %>
<% end %>
views/users/new.html.erb
<h1>Successfully registered</h1>
views/users/success.html.erb
<h1>Email sent successfully</h1>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
end
def create
#user=User.new(users_params)
if #user.save
UserMailer.registration_confirmation(#user).deliver
redirect_to :action => 'success'
else
render :'index'
end
end
def new
end
def success
end
private
def users_params
params.require(:user).permit(:name, :email)
end
end
views/user_mailer/registration_confirmation.text.erb
<%= #user.name%>
<h1>Thank you for registering</h1>
Click <%= link_to "here",users_new_path %>
mailer/user_mailer.rb
class UserMailer < ApplicationMailer
default :from => "w5call.w5rtc#gmail.com"
def registration_confirmation(user)
#user=user
mail(:to => user.email, :subject => "Registered")
end
end
config/initializers/setup_mail.rb
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "w5call.w5rtc#gmail.com",
:password => "w5rtc123#",
:authentication => "plain",
:enable_starttls_auto => true
}
endActionMailer::Base.default_url_options[:host] = "localhost:3000"
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.
config.action_mailer.raise_delivery_errors = 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
# 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
config.action_mailer.delivery_method = :smtp
end
routes.rb
Rails.application.routes.draw do
root 'users#index'
post "users/create" => "users#create"
get "users/success" => "users#success"
get "users/new" => "users#new"
end
Actually i was referring this tutorial.I am using rails-4 and ruby 1.9.3.Please help me to resolve this error.

Base protocol (https://) for every render/redirect_to call

is there a way i can set up a base protocol to use
render :action => "myaction"
redirect_to :action => "myaction"
instead of calling
render :action => "myaction", :protocol => "https://"
redirect_to :action => "myaction", :protocol => "https://"
every time?
Simply use config.force_ssl = true in your environment configuration.
# config/application.rb
module MyApp
class Application < Rails::Application
config.force_ssl = true
end
end
You can also selectively enable https depending on the current Rails environment. For example, you might want to keep HTTPS turned off on development, and enable it on staging/production.
# config/application.rb
module MyApp
class Application < Rails::Application
config.force_ssl = false
end
end
# config/environments/production.rb
MyApp::Application.configure do
config.force_ssl = true
end
Behind the scenes, Rails adds the awesome Rack::SSL Rack middleware to your application middleware stack. Rack::SSL automatically filters the request, redirects not-HTTPS requests to the corresponding HTTPS path and applies some additional improvements to make sure your HTTPS request is secure.

Resources