【问题标题】:how can I replace database value within email body如何替换电子邮件正文中的数据库值
【发布时间】:2020-05-14 01:17:48
【问题描述】:

我正在通过我的应用程序发送电子邮件。由于我必须发送不同类型的邮件,我使用数据库来保存邮件,然后获取邮件正文的邮件。
这就是我获取通知的方式。

def send_share_company(address, cid, from, council_id)

co = Council.find_by(id: council_id)
c = Company.find_by(id: cid)
@a = address.split(',')
@f = from
n = Notification.find_by(id: 'ad4e3718-0689-413b-8a52-96887e0d2aba')


  message =n["body"]

  from = Email.new(email: 'noreply@my.network', name: "my Network")
  subject =  + cl["title"] + ' - Event of the Week: ' + c["name"]
  to = Email.new(email: a.to_s)
  content = Content.new(type: 'text/html', value: message)
  mail = Mail.new(from, subject, to, content)

  sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
  pp sg.client.mail._("send").post(request_body: mail.to_json) unless Rails.env.staging?
end

我将通知正文保存在数据库中,如下所示。

你好,
#{@f} 认为你应该看看公司,#{c["name"]}

我想用这些值替换 #{@f} 和 #{c["name"]}。但它不会发生。电子邮件发送而不替​​换值。我该如何解决这个问题。

【问题讨论】:

    标签: ruby-on-rails email


    【解决方案1】:

    字符串插值仅发生在字符串文字中。不在从文件、数据库或用户输入加载的字符串中——想象一下那会有多危险。

    为了扩展插值,您必须引用内容并对其进行评估。这远非理想。一个更好的主意是使用像ERB 这样的模板引擎。

    Hello,
    <%= #{@f} %> thought you should take a look at the company, <%= #{c["name"]} %>.
    

    require 'erb'
    template = ERB.new(n.body)
    rendered = template.render(binding)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 2014-01-29
      • 2018-09-03
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多