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

ruby-on-rails – ActionMailer – 如何添加附件?,第1张

概述看起来很简单,但我无法让它工作.这些文件在Web应用程序上从S3工作正常,但是当我通过下面的代码将它们发送出去时,文件已损坏. App Stack:rails 3,heroku,paperclip s3 这是代码: class UserMailer < ActionMailer::Base# Add Attachments if anyif @comment.attachments.count 看起来很简单,但我无法让它工作.这些文件在Web应用程序上从S3工作正常,但是当我通过下面的代码将它们发送出去时,文件已损坏.

App Stack:rails 3,heroku,paperclip s3

这是代码:

class UserMailer < ActionMailer::Base# Add Attachments if anyif @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  endendmail( :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 httpSrequire '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  endend

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

总结

以上是内存溢出为你收集整理的ruby-on-rails – ActionMailer – 如何添加附件?全部内容,希望文章能够帮你解决ruby-on-rails – ActionMailer – 如何添加附件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1292004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存