【问题标题】:Render HTML string in email body with ActionMailer class in Ruby使用 Ruby 中的 ActionMailer 类在电子邮件正文中呈现 HTML 字符串
【发布时间】:2018-07-26 09:25:01
【问题描述】:

我正在尝试使用 ActionMailer 类在 ROR 中发送邮件。

我创建了一个邮件对象,例如:

mail(to: 'xyz@gmail.com', subject: "some subject text", body: template)

这里的模板是一个字符串,其中包含要在邮件正文中呈现的 HTML。

当我尝试上述声明时,HTML 字符串会像在 Gmail 或任何其他客户端中一样显示,而不是被渲染。

我知道我可以制作一个单独的 ERB 文件以供查看和 邮件视图位于 app/views/name_of_mailer_class 目录。

但我想渲染从另一个内联源生成的 HTML 字符串,而不将其存储在文件中。

我也尝试过我在下面的链接中找到的这种方法,但它产生了相同的结果。 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 

【问题讨论】:

  • 只需将content_type: 'text/html' 添加到mail

标签: ruby-on-rails ruby render actionmailer


【解决方案1】:

终于找到了一种无需任何视图文件即可呈现 HTML 的方法。使 HTML 字符串 html_safe 在电子邮件客户端中呈现 HTML。

mail(to: 'xyz@gmail.com', subject: 'some subject text') do |format| format.html { render html: template.to_s.html_safe }

【讨论】:

    【解决方案2】:

    你可以这样做:

    @template = template.html_safe
    mail(to: 'xyz@gmail.com', subject: "some subject text")
    

    在您的 ActionMailer 视图中 app/views/name_of_mailer_class 只需将您的字符串呈现为

    <%= @template %>
    

    希望对你有帮助

    【讨论】:

    • 这需要我在视图文件夹中创建一个单独的文件。我正在寻找一种无需制作任何额外文件即可呈现模板的方法。
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 2015-04-11
    • 2012-07-31
    相关资源
    最近更新 更多