Module: Mail::EmbedHTMLImages

Included in:
Message
Defined in:
lib/mail/embed-html-images.rb,
lib/mail/embed-html-images/version.rb

Constant Summary collapse

MIME_TO_EXTENSION =
{
  'image/png'  => 'png',
  'image/jpeg' => 'jpg',
  'image/gif'  => 'gif',
}
VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#embed_html_imagesObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mail/embed-html-images.rb', line 13

def embed_html_images
  @_embedded_images ||= {}
  current_images = {}

  # Don't do anything if we don't have an html part
  return unless html_part

  # Find all img tags in the html part
  new_html = html_part.body.to_s.gsub(/<img (.*?)src=((?<![\\])['"])(http(?:.(?!(?<![\\])\2))*.?)\2([^>]*)>/) do |match_string|
    img_src_original = $3
    img_src_hash = Digest::SHA1.hexdigest img_src_original

    # Check to see whether or not we already have this image: if not, attach it
    if !@_embedded_images[img_src_hash]
      response = Net::HTTP.get_response(URI(img_src_original))
      attachment_filename = img_src_hash + '.' + MIME_TO_EXTENSION[response["content-type"]]
      add_file filename: attachment_filename, content: response.body
      @_embedded_images[img_src_hash] = attachment_filename
    end
    current_images[img_src_hash] = @_embedded_images[img_src_hash]

    attached_image = attachments[@_embedded_images[img_src_hash]]

    # Create new src using content id of attachment
    img_src_new = "cid:#{attached_image.cid}"

    # Return substitute with new src
    "<img #{$1}src=\"#{img_src_new}\"#{$4}>"
  end

  # Detach any images that are no longer needed
  @_embedded_images.each do |hash, filename|
    if !current_images[hash]
      self.parts.delete_if { |p| p.filename == filename }
    end
  end
  @_embedded_images = current_images

  html_part.body = new_html
end