ActionMailer - 如何添加附件? [英] ActionMailer - How to Add an attachment?
问题描述
看起来很简单,但我一直无法让它工作.这些文件在网络应用程序上的 S3 中运行良好,但是当我通过下面的代码将它们通过电子邮件发送出去时,文件已损坏.
Seems simple enough but I haven't been able to get it to work. The files work fine from S3 on the web app, but when I email them out via the code below, the files are corrupt.
应用程序堆栈:rails 3、heroku、回形针 + s3
App Stack: rails 3, heroku, paperclip + s3
代码如下:
class UserMailer < ActionMailer::Base
# Add Attachments if any
if @comment.attachments.count > 0
@comment.attachments.each do |a|
require 'open-uri'
open("#{Rails.root.to_s}/tmp/#{a.attachment_file_name}", "wb") do |file|
file << open(a.authenticated_url()).read
attachments[a.attachment_file_name] = File.read("#{Rails.root.to_s}/tmp/#{a.attachment_file_name}")
end
end
end
mail( :to => "#{XXXX}",
:reply_to => "XXXXX>",
:subject => "XXXXXX"
)
a.authenticated_url() 只是给了我一个指向 s3 的 URL 来获取文件(任何类型),我检查了这个,工作正常.与我保存临时文件的方式有关的事情一定是破坏了 ActionMailer 附件.
a.authenticated_url() just gives me a URL to s3 to get the file (of any type), I checked this, works fine. Something to do with the way I'm saving the tempfile must be breaking the ActionMailer Attachment.
有什么想法吗?
推荐答案
这可能会更好,因为它不涉及文件系统(这在 Heroku 上经常出现问题):
This might work better because it doesn't touch the filesystem (which is often problematic on Heroku):
require 'net/http'
require 'net/https' # You can remove this if you don't need HTTPS
require 'uri'
class UserMailer < ActionMailer::Base
# Add Attachments if any
if @comment.attachments.count > 0
@comment.attachments.each do |a|
# Parse the S3 URL into its constituent parts
uri = URI.parse a.authenticated_url
# Use Ruby's built-in Net::HTTP to read the attachment into memory
response = Net::HTTP.start(uri.host, uri.port) { |http| http.get uri.path }
# Attach it to your outgoing ActionMailer email
attachments[a.attachment_file_name] = response.body
end
end
end
我认为这不会导致任何额外的内存问题,因为在任何情况下,您都必须在 attachments[a.attachment_file_name]
行将文件数据加载到内存中.
I don't think this will cause any extra memory issues because in any case you have to load the file's data into memory on the attachments[a.attachment_file_name]
line.
这篇关于ActionMailer - 如何添加附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!