Ajith
Ajith

Reputation: 345

passing the entire email body as a string and rendering email in rails

I'm working on a project which is in rails 5.2. I'm using the rails action mailer to send the email.

I have to send the entire email template as an input to an action mailer.

so far I have overridden the mail method of the action mailer.

class UAMailer < ActionMailer::Base
  def mail(headers = {}, &block)
    super(headers.merge(template_path: template_path), &block)
  end
end

I'm calling this from one method called say send_email.

def send_email(user, subject)
  mail(to: user.email, subject: subject)
end

then I have a normal send_email.html.erb a template where the actual mailer body is written.

<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
 </head>
<body>
  <p>Dear <%= @user.username %>,</p>
  <p>Testing</p>
</body>

I want to pass this entire body as an input to the mail method defined earlier. entire HTML body tag I need to pass to the overridden mail method.

def send_email(user, subject, body)
  mail(to: user.email, subject: subject, body: body)
end

Upvotes: 0

Views: 1377

Answers (1)

Pardeep Dhingra
Pardeep Dhingra

Reputation: 3946

Any instance variable added under email action is directly accessible in its corresponding email template.

For. Eg.

@body = body 

and in the template, you can call

<%= @body.html_safe %>

For HTML safe content html_safe

Upvotes: 1

Related Questions