Hi I have to access the current user into my action mailer, but I getting following error
undefined local variable or method `current_user' for #<WelcomeMailer:0xa9e6b230>
by using this link I am using application helper for getting the current user. Here is my WelcomeMailer
class WelcomeMailer < ActionMailer::Base
layout 'mail_layout'
def send_welcome_email
usr = find_current_logged_in_user
Rails.logger.info("GET_CURRENT_USER_FROM_Helper-->#{usr}")
end
end
and my application helper is as follows
def find_current_logged_in_user
#@current_user ||= User.find_by_remember_token(cookies[:remember_token])
# @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
Rails.logger.info("current_user---> #{current_user}")
current_user
end
Also I tried with session and cookies. So how can I resolve this error or is there any other method for accessing current user in action mailer.
I am using Rails 3.2.14 and ruby ruby 2.1.0
Once the Rails mailer and Gmail settings are properly configured, we can easily send other emails from other controller actions by generating and setting up new mailers in much the same way. :) I just wanted to thank you for writing out this detailed tutorial.
What is action mailer? According to the Ruby on Rails Guides, “Action Mailer allows you to send emails from your application using mailer classes and views”. Before going any further, if you aren’t familiar with the Model-View-Controller pattern, it might help to take some time to read up on it as Action Mailer relies on the same design patterns.
To get started, we will first need to create a mailer which is easy to do with Rails' generate mailer command. In this case, the mailer will be used in the OrdersController so we'll name it OrderMailer:
Now, in your Rails app mailer settings, replace the <gmail_password> with the new app password instead. If you don't use 2-step verification, you will have to allow your account to be accessed by "less secure apps". In your Google settings under the "Security" tab, look for the "Less secure app access" section and click "Turn on access".
Don't try to access current_user
from inside a Mailer. Instead, pass the user into the mailer method. For example,
class WelcomeMailer < ActionMailer::Base
def welcome_email(user)
mail(:to => user.email, :subject => 'Welcome')
end
end
To use it from within a contoller, where you have access to current_user
:
WelcomeMailer.welcome_email(current_user).deliver
From within a model:
class User < ActiveRecord::Base
after_create :send_welcome_email
def send_welcome_email
WelcomeMailer.welcome_email(self).deliver
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With