加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ActionMailer – 如何添加附件?

发布时间:2020-12-17 03:09:52 所属栏目:百科 来源:网络整理
导读:看起来很简单,但我无法让它工作.这些文件在Web应用程序上从S3工作正常,但是当我通过下面的代码将它们发送出去时,文件已损坏. App Stack:rails 3,heroku,paperclip s3 这是代码: class UserMailer ActionMailer::Base# Add Attachments if anyif @comment.a
看起来很简单,但我无法让它工作.这些文件在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"
      )

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

有任何想法吗?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读