[英]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
mailer 类,你可以通过只发送attached_file来简化附件,如果你想用其他名字重命名它,文件名是灵活的。
def send_invoice(attachment)
if attachment.present?
attachments[attachment[:filename]] = {content: attachment[:file]}
end
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.