以字符串形式传递整个电子邮件正文并在Rails中呈现电子邮件

时间:2019-12-23 18:14:02

标签: ruby-on-rails ruby-on-rails-5 actionmailer ruby-on-rails-5.2

我正在研究Rails 5.2中的项目。我正在使用Rails Action Mailer发送电子邮件。

我必须将整个电子邮件模板作为输入发送给操作邮件程序。

到目前为止,我已经覆盖了动作邮件程序的邮件方法。

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

我正在从一种称为“ send_email”的方法中调用它。

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

然后我有一个普通的 send_email.html.erb 模板,用于编写实际的邮件正文。

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

我希望将整个正文作为先前定义的mail方法的输入。整个HTML正文标记,我需要传递给重写的mail方法。

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

1 个答案:

答案 0 :(得分:1)

在电子邮件操作下添加的任何实例变量都可以在其相应的电子邮件模板中直接访问。

为。例如。

@body = body 

在模板中,您可以调用

<%= @body.html_safe %>

对于HTML安全内容html_safe