【问题标题】:ActionMailer - How to Add an attachment?ActionMailer - 如何添加附件?
【发布时间】:2011-01-10 23:08:34
【问题描述】:

看起来很简单,但我无法让它工作。这些文件在网络应用程序上的 S3 工作正常,但是当我通过下面的代码将它们通过电子邮件发送出去时,文件已损坏。

应用堆栈:rails 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 的 URL 来获取文件(任何类型),我检查了这个,工作正常。与我保存临时文件的方式有关的事情一定是破坏了 ActionMailer 附件。

有什么想法吗?

【问题讨论】:

  • 你能确认从S3下载的tmp文件没问题吗?

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


【解决方案1】:

这可能会更好,因为它不涉及文件系统(这在 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] 行的内存中。

【讨论】:

  • 效果很好...当您需要写出字符串(模板渲染的结果)并将其附加为 html 文件以进行发送时,设置内容类型非常有用
  • 如何将图像作为附件发送,图像从另一台服务器发送并作为附件发送到邮件???
猜你喜欢
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多