2017-07-23 11:17:16 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-08-06 13:01:31 -04:00
|
|
|
require "base64"
|
2015-05-04 14:46:51 -04:00
|
|
|
|
|
|
|
module ActionMailer
|
|
|
|
# Implements a mailer preview interceptor that converts image tag src attributes
|
2018-01-11 17:13:41 -05:00
|
|
|
# that use inline cid: style URLs to data: style URLs so that they are visible
|
2016-03-03 09:01:32 -05:00
|
|
|
# when previewing an HTML email in a web browser.
|
2015-05-04 14:46:51 -04:00
|
|
|
#
|
2015-05-29 14:19:17 -04:00
|
|
|
# This interceptor is enabled by default. To disable it, delete it from the
|
2015-05-04 14:46:51 -04:00
|
|
|
# <tt>ActionMailer::Base.preview_interceptors</tt> array:
|
|
|
|
#
|
|
|
|
# ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor)
|
|
|
|
#
|
|
|
|
class InlinePreviewInterceptor
|
2016-10-28 23:05:58 -04:00
|
|
|
PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i
|
2015-05-04 14:46:51 -04:00
|
|
|
|
|
|
|
include Base64
|
|
|
|
|
|
|
|
def self.previewing_email(message) #:nodoc:
|
|
|
|
new(message).transform!
|
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(message) #:nodoc:
|
|
|
|
@message = message
|
|
|
|
end
|
|
|
|
|
|
|
|
def transform! #:nodoc:
|
|
|
|
return message if html_part.blank?
|
|
|
|
|
2017-01-30 22:36:23 -05:00
|
|
|
html_part.body = html_part.decoded.gsub(PATTERN) do |match|
|
2015-05-04 14:46:51 -04:00
|
|
|
if part = find_part(match[9..-2])
|
|
|
|
%[src="#{data_url(part)}"]
|
|
|
|
else
|
|
|
|
match
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
message
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2018-03-29 22:29:55 -04:00
|
|
|
attr_reader :message
|
2015-05-04 14:46:51 -04:00
|
|
|
|
|
|
|
def html_part
|
|
|
|
@html_part ||= message.html_part
|
|
|
|
end
|
|
|
|
|
|
|
|
def data_url(part)
|
|
|
|
"data:#{part.mime_type};base64,#{strict_encode64(part.body.raw_source)}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def find_part(cid)
|
2016-08-16 03:30:11 -04:00
|
|
|
message.all_parts.find { |p| p.attachment? && p.cid == cid }
|
2015-05-04 14:46:51 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|