ActionMailer - 如何添加附件?

AnA*_*ice 4 ruby-on-rails ruby-on-rails-3

看起来很简单,但我无法让它工作.这些文件在Web应用程序上从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"
      )
Run Code Online (Sandbox Code Playgroud)

a.authenticated_url()只给我一个s3的URL来获取文件(任何类型),我检查了一下,工作正常.与我保存临时文件的方式有关,必须打破ActionMailer附件.

有任何想法吗?

Sea*_*ere 7

这可能会更好,因为它不会触及文件系统(在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
Run Code Online (Sandbox Code Playgroud)

我不认为这会导致任何额外的内存问题,因为无论如何你必须将文件的数据加载到attachments[a.attachment_file_name]线路上的内存中.