We recently had to embed images into our emails that were being sent with Actionmailer, and as such we turned to the inline_attachment plugin to achieve this. It very easily parses your mail output and overrides the ActionView path_to_image helper to attach the file and create an appropriate path to the attached image inside the email while splitting your mail into appropriate parts as necessary.
What we needed to do though was embed a dynamically generated image into the email. The image didn’t exist on the file system previously so we couldn’t use the standard image_tag helper that inline_attachment was patching.
So we extended ActionView to include a new tag helper attach_image_file that uses the existing inline_attachment part management and just a properly referenced image. The methods from inline_attachment take care of attaching the file to the email and splitting the mail content into the appropriate parts.
Here’s my code. I just added it into my initializers directory :
module ActionView
module Helpers
module AssetTagHelper
def attach_image_file(file)
@part_container ||= @controller
if @part_container.is_a?(ActionMailer::Base) or @part_container.is_a?(ActionMailer::Part)
basename = "barcode.gif"
ext = basename.split('.').last
cid = Time.now.to_f.to_s + "#{basename}@inline_attachment"
@part_container.inline_attachment(:content_type => "image/#{ext}",
:body => file,
:filename => basename,
:cid => "<#{cid}>",
:disposition => "inline")
return "
"
end
end
end
end
end
It did what we need, and allows us to properly inline a dynamic image. You could use similar code to inline pretty much anything that your target mail reader supports. Apple Mail for instance may provide PDF previews.
