Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get email address in the "to" field from ActionMailer view?

I want to make a method accessible from a mailer view that returns a boolean depending on the user that the email is being sent to.

For example, let's say the user has an attribute is_subscriber which can be true or false. The method would contain something like this:

def show_banner?
  FeatureManager.is_feature_available?(:subscription_banners) && !user.is_subscriber
end

I want to access this method from within the mailer views.

The problem is, I have a lot of mailers in my app (UserMailer, SubscriptionMailer, FollowUpMailer) and relying on an instance variable @user for each mailer seems a bit dangerous.

Is there any way I can access the email address from the "to" field as in this example so I can find the user by his email address:

mail :to => @user.email, :subject => I18n.t('welcome_mail.subject')

Is it a good idea to do that or is there a more generic way of making such helper method?

like image 481
Cristian Avatar asked Jun 20 '12 14:06

Cristian


1 Answers

You can use @_message in actionview which gives you access to the message object from which you can access fields like 'to', 'from'.

I had a case where I need a unsubscribe button on all mails, So placed it in my layout which was used across mailers. I used the above solution to find the mail receiver and implement unsubscribe for the respective mail.

like image 50
ramkumar Avatar answered Oct 10 '22 09:10

ramkumar