I'm trying to do a conditional render of a different template from ActionMailer (Rails 3.1.1). I want most users to get the normal welcome.html.erb
template, but some users to get the special welcome_photographer.html.erb
template. This type of thing works in ActionController:
# (in /app/mailers/user_mailer.rb) def welcome(user) @user = user mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...") render "welcome_photographer" if @user.is_photographer end
But the render doesn't work -- everyone gets the standard welcome.html.erb
even if @user.is_photographer == true
Then the preview will be available in http://localhost:3000/rails/mailers/user_mailer/welcome_email. If you change something in app/views/user_mailer/welcome_email. html. erb or the mailer itself, it'll automatically reload and render it so you can visually see the new style instantly.
Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.
You shouldn't try to do anything after you call mail()
. However, to choose another template, you should pass :template_name
as an option. For example:
template = @user.is_photographer ? "welcome_photographer" : "welcome" mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...", :template_name => template)
The solution from Sean Hill doesn't work for me (Rails 3.2+). template_name
seems to be ignored. What worked for me is something like this:
mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...") do |format| format.html { render 'templatename' } 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