ActionMailer - 如何添加附件?

时间:2010-12-05 18:18:57

标签: ruby-on-rails ruby-on-rails-3

看起来很简单,但我无法让它发挥作用。这些文件可以在网络应用程序的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附件。

有什么想法吗?

1 个答案:

答案 0 :(得分: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

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