Raman Preet Singh
Raman Preet Singh

Reputation: 314

Render HTML string in email body with ActionMailer class in Ruby

I'm trying to send mail in ROR using ActionMailer class.

I have created a mail object like :

mail(to: '[email protected]', subject: "some subject text", body: template)

Here template is a string which contains the HTML to be rendered in the mail body.

When I'm trying the above declaration, the HTML string is getting displayed as it is in Gmail or any other client rather then getting rendered.

I'm aware of the fact that I can make a separate ERB file for view and mailer views are located in the app/views/name_of_mailer_class directory.

But I want to the render the HTML string I'm generating from another source inline without storing it in a file.

I have also tried this method I found in the link below, but it is producing the same result. http://carols10cents.github.io/versioned_rails_guides/v3.2.2/action_mailer_basics.html

mail(:to => user.email,
         :subject => "Welcome to My Awesome Site") do |format|
      format.html { render 'another_template' }
      format.text { render :text => 'Render text' }
    end 

Upvotes: 2

Views: 4894

Answers (2)

Raman Preet Singh
Raman Preet Singh

Reputation: 314

Finally found a way to render HTML without any views file. Making the HTML string html_safe rendered the HTML in email clients.

mail(to: '[email protected]', subject: 'some subject text') do |format| format.html { render html: template.to_s.html_safe }

Upvotes: 9

Snoobie
Snoobie

Reputation: 760

You could do something like this:

@template = template.html_safe
mail(to: '[email protected]', subject: "some subject text")

And in your ActionMailer View app/views/name_of_mailer_class just render your string as

<%= @template %>

Hope it helps

Upvotes: 3

Related Questions