gotqn
gotqn

Reputation: 43636

Why "Action Mailer" is not rendering the email template?

I am using "Action Mailer" in Ruby on Rails application to send emails. I have the following action mailer:

class SecurityUserMailer < ActionMailer::Base

  default from: '[email protected]'

  def password_reset(security_user)
    @security_user = security_user
    mail to: security_user.email, subject: 'Password Reset'
  end

  def email_confirmation(security_user)
    @security_user = security_user
    mail to: security_user.email, subject: 'Account Created'
  end

end

I am successfully sending emails but the second method (email_confirmation) is not using the corresponding template.

The email templates are in views/security_users_mailer folder and named as follows:

  1. email_confirmation.txt.erb
  2. password_reset.txt.erb

Why only the password_reset template is used?

Note, firstly, I thought that maybe there is something wrong with the code in my template but then I replace it with text content and it is not rendered again.

Upvotes: 5

Views: 3384

Answers (3)

gotqn
gotqn

Reputation: 43636

The issue was caused by file extension TYPO. I have

email_confirmation.txt.erb

and a mailer template should be with extension text or html.

As you see from the official docs - the template with the same mailer action is used by default if exists.

Upvotes: 4

random-forest-cat
random-forest-cat

Reputation: 35914

Rails 4 I had this same issue, but mine was caused by having an empty layout in layouts/mailer.html.erb

Upvotes: 4

Deej
Deej

Reputation: 5352

I believe an alternative would be to specify the template you would like to render the following is an example how you may go about this

class SecurityUserMailer < ActionMailer::Base
  default from: '[email protected]'
  def password_reset(security_user)
    @security_user = security_user
    mail to: security_user.email, subject: 'Password Reset'
  end

  def email_confirmation(security_user)
    @security_user = security_user
    mail (:to =>  security_user.email, 
          :subject => 'Account Created', 
          :template_path => 'email_confirmation.txt.erb',
          :template_name => 'another')
  end
end

Take a look at the following should provide some further insight:

Mailer Views

or look at

Api Ruby on Rails You will see example where it says Or even render a special view so that alternatively you could have inside your mail block the following:

mail (:to =>  security_user.email, 
              :subject => 'Account Created') do |format|
               format.html { render 'another_template' }
               format.text { render :text => 'email_confirmation.txt.erb' }
      end

This should shed some light on what you are trying to accomplish

Upvotes: 2

Related Questions