diff options
author | Andrew White <andyw@pixeltrix.co.uk> | 2015-05-04 10:43:52 +0100 |
---|---|---|
committer | Andrew White <andyw@pixeltrix.co.uk> | 2015-05-04 10:56:59 +0100 |
commit | 60239f3e5a3303b4135e30469ba7dbf27890008d (patch) | |
tree | 4da42b69cae65df57d5caaab6a7d9259846204a5 /actionmailer/lib | |
parent | 9f39d3126fe85c94198371fd1cccd408c268529c (diff) | |
download | rails-60239f3e5a3303b4135e30469ba7dbf27890008d.tar.gz rails-60239f3e5a3303b4135e30469ba7dbf27890008d.tar.bz2 rails-60239f3e5a3303b4135e30469ba7dbf27890008d.zip |
Add support for inline images to mailer previews
Use a preview interceptor to search for inline cid: urls in src
attributes and convert them to data urls.
Diffstat (limited to 'actionmailer/lib')
-rw-r--r-- | actionmailer/lib/action_mailer/preview.rb | 50 |
1 files changed, 49 insertions, 1 deletions
diff --git a/actionmailer/lib/action_mailer/preview.rb b/actionmailer/lib/action_mailer/preview.rb index 44cf6665ba..4888eac345 100644 --- a/actionmailer/lib/action_mailer/preview.rb +++ b/actionmailer/lib/action_mailer/preview.rb @@ -1,9 +1,57 @@ require 'active_support/descendants_tracker' +require 'base64' module ActionMailer module Previews #:nodoc: extend ActiveSupport::Concern + class InlineAttachments #:nodoc: + PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i + + include Base64 + + attr_reader :message + + def self.previewing_email(message) + new(message).transform! + end + + def initialize(message) + @message = message + end + + def transform! + return message if html_part.blank? + + html_source.gsub!(PATTERN) do |match| + if part = find_part(match[9..-2]) + %[src="#{data_url(part)}"] + else + match + end + end + + message + end + + private + def html_part + @html_part ||= message.html_part + end + + def html_source + html_part.body.raw_source + end + + def data_url(part) + "data:#{part.mime_type};base64,#{urlsafe_encode64(part.body.raw_source)}" + end + + def find_part(cid) + message.all_parts.find{ |p| p.attachment? && p.cid == cid } + end + end + included do # Set the location of mailer previews through app configuration: # @@ -21,7 +69,7 @@ module ActionMailer # :nodoc: mattr_accessor :preview_interceptors, instance_writer: false - self.preview_interceptors = [] + self.preview_interceptors = [ActionMailer::Previews::InlineAttachments] end module ClassMethods |