2010-12-05 63 views
3

似乎很簡單,但我還沒有能夠得到它的工作。這些文件在網絡應用程序中從S3正常工作,但是當我通過下面的代碼通過電子郵件發送出去時,這些文件已損壞。ActionMailer - 如何添加附件?

應用程序堆棧:軌道3,Heroku的,回形針+ 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來獲取文件(任何類型),我檢查了這個,工作正常。與我保存臨時文件的方式有關的事情必須打破ActionMailer附件。

任何想法?

+0

你能確認從S3下載的tmp文件可以嗎? – ffoeg 2011-01-09 17:48:20

回答

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]行的內存中。

+0

很好用...設置內容類型對於需要寫出字符串(模板呈現的結果)並將其附加爲用於發送的html文件時效果很好 – Avishai 2011-11-06 15:02:05