在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
如何将变量从控制器传递到邮件文件?
答案 0 :(得分:0)
# controller
InvoiceMailer.send_invoice(attachment).deliver
# mailer
def send_invoice(attachment)
attachments['test-bill'] = File.read(attachment)
...
end
答案 1 :(得分:0)
这对我有用:
在控制器中
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