ActionMailer - How to add an attachment?

Seems pretty simple, but I couldn't get it to work. Files work fine with S3 in a web application, but when I send them via email using the code below, the files are corrupted.

Application stack: rails 3, hero, clip + s3

Here is the code:

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 () just gives me the url for s3 to get the file (of any type), I checked this works fine. Something related to the way I save tempfile should violate the ActionMailer application.

Any ideas?

+3
source share
1 answer

This might work better because it does not concern the file system (which is often problematic on 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 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].

+7

Source: https://habr.com/ru/post/1778611/


All Articles