【问题标题】:Send email with attachments action Mailer Ruby on Rails发送带有附件操作的电子邮件 Mailer Ruby on Rails
【发布时间】:2020-01-04 03:48:57
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby email actionmailer


    【解决方案1】:
    # controller
    InvoiceMailer.send_invoice(attachment).deliver
    
    # mailer
    def send_invoice(attachment)
      attachments['test-bill'] = File.read(attachment)
      ...
    end
    

    【讨论】:

      【解决方案2】:

      这对我有用:

      在控制器中

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

      mailer类,你可以通过只发送attached_file来简化附件,如果你想用其他名字重命名它,文件名只是灵活的。

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

      【讨论】:

      • 也可以,但对我来说最好是:attached_file = tmp_file.pathattachments[attachment[:filename]] = File.read(attachment[:file])
      猜你喜欢
      • 1970-01-01
      • 2014-12-05
      • 2012-01-06
      • 1970-01-01
      • 2012-08-02
      • 2016-12-18
      • 2013-05-21
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多