Skip to content

Instantly share code, notes, and snippets.

@Agowan
Created May 6, 2015 12:32
Show Gist options
  • Save Agowan/d213e77870fbd0754c4a to your computer and use it in GitHub Desktop.
Save Agowan/d213e77870fbd0754c4a to your computer and use it in GitHub Desktop.
Store raw email in attachment with rails
# encoding: UTF-8
class Email < ActiveRecord::Base
has_attached_file :raw
after_save :remove_file
# ===========================================================================
# Public instance methods
# ===========================================================================
def mail=(value)
return unless mail
@file_name = "#{Dir.tmpdir}/#{mail.object_id}.gzip"
raw_message = mail.to_s rescue mail.raw_source
file = File.open(@file_name,"w:ASCII-8BIT") do |f|
f.write(zip.compress(raw_message))
end
raw_file = File.new(@file_name)
self.raw = raw_file
ensure
raw_file.close unless raw_file.closed?
end
def mail
begin
@mail ||= Mail.new(zip.decompress(tempfile.read))
ensure
@tempfile.close! if @tempfile
end
@mail
end
# ===========================================================================
# Private instance methods
# ===========================================================================
private
def tempfile
@tempfile ||= Paperclip.io_adapters.for(self.raw).tempfile
end
def zip
ActiveSupport::Gzip
end
def remove_file
begin
if @file_name && File.exists?(@file_name)
#puts "Removing #{@file_name}"
File.delete(@file_name)
end
rescue
puts "Failed to remove file: #{@file_name} in Email object"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment