在 Rails 上发送带有附件的电子邮件操作 Mailer Ruby

Send email with attachments action Mailer Ruby on Rails

https://edgeguides.rubyonrails.org/action_mailer_basics.html 之后,我尝试将我的应用配置为发送带附件的电子邮件,但出现错误 NameError (undefined local variable or method attachment for #<InvoiceMailer:0x00007fde0d7bfe88> Did you mean? attachments)

这是我控制器中的内容:

        array_docs.each do |doc| 
            decoded_doc = URI.decode(doc)               

            tmp_file = Tempfile.new(['bill', '.pdf'])
            tmp_file.binmode
            open(decoded_doc, "Authorization" => bearer_token) do |url_file|
               tmp_file.write(url_file.read)
               tmp_file.rewind
               tmp_file.read
               attachment = tmp_file.path
               InvoiceMailer.send_invoice.deliver
            end
        end

这是我的发票邮寄程序:

class InvoiceMailer < ApplicationMailer

default :from => 'Test <no-reply@test.co>'

  def send_invoice
    attachments['test-bill'] = File.read(attachment)
    mail(to: "steven@test.com",
    subject: "check if it works")
  end
end

还有我的看法send_invoice.html.erb

<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <h1>Test to check if it works </h1>
    <p>Hello world</p>
  </body>
</html>

添加到我的 development.rb 并重新启动我的服务器:

config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

如何将变量从控制器传递到邮件文件?

# controller
InvoiceMailer.send_invoice(attachment).deliver

# mailer
def send_invoice(attachment)
  attachments['test-bill'] = File.read(attachment)
  ...
end

这对我有用:

在控制器中

attached_file = tmp_file.read

attachment = Array.new
attachment = {filename: "nameoffile.something", file: attached_file}
InvoiceMailer.send_invoice(attachment).deliver

邮件程序 class,您可以通过仅发送 attached_file 来简化附件,如果您想用其他名称重命名文件名,请灵活一些。

def send_invoice(attachment)
   if attachment.present? 
     attachments[attachment[:filename]] = {content: attachment[:file]}
   end
  ...
end