Class: Premailer

Inherits:
Object
  • Object
show all
Includes:
CssParser, HtmlToPlainText, Warnings
Defined in:
lib/premailer/premailer.rb

Overview

Premailer by Alex Dunae (dunae.ca, e-mail ‘code’ at the same domain), 2008-10

Premailer processes HTML and CSS to improve e-mail deliverability.

Premailer’s main function is to render all CSS as inline style attributes. It also converts relative links to absolute links and checks the ‘safety’ of CSS properties against a CSS support chart.

Example

premailer = Premailer.new('http://example.com/myfile.html', :warn_level => Premailer::Warnings::SAFE)

# Write the HTML output
fout = File.open("output.html", "w")
fout.puts premailer.to_inline_css
fout.close

# Write the plain-text output
fout = File.open("ouput.txt", "w")
fout.puts premailer.to_plain_text
fout.close

# List any CSS warnings
puts premailer.warnings.length.to_s + ' warnings found'
premailer.warnings.each do |w|
  puts "#{w[:message]} (#{w[:level]}) may not render properly in #{w[:clients]}"
end

premailer = Premailer.new(html_file, :warn_level => Premailer::Warnings::SAFE)
puts premailer.to_inline_css

Defined Under Namespace

Modules: Warnings

Constant Summary collapse

VERSION =
'1.7.0'
CLIENT_SUPPORT_FILE =
File.dirname(__FILE__) + '/../../misc/client_support.yaml'
RE_UNMERGABLE_SELECTORS =
/(\:(visited|active|hover|focus|after|before|selection|target|first\-(line|letter))|^\@)/i
{
  'h1' => {'text-align' => 'align'},
  'h2' => {'text-align' => 'align'},
  'h3' => {'text-align' => 'align'},
  'h4' => {'text-align' => 'align'},
  'h5' => {'text-align' => 'align'},
  'h6' => {'text-align' => 'align'},
  'p' => {'text-align' => 'align'},
  'div' => {'text-align' => 'align'},
  'blockquote' => {'text-align' => 'align'},
  'body' => {'background-color' => 'bgcolor'},
  'table' => {'background-color' => 'bgcolor'},
  'tr' => {'text-align' => 'align', 'background-color' => 'bgcolor'},
  'th' => {'text-align' => 'align', 'background-color' => 'bgcolor', 'vertical-align' => 'valign'},
  'td' => {'text-align' => 'align', 'background-color' => 'bgcolor', 'vertical-align' => 'valign'},
  'img' => {'float' => 'align'}
}
WARN_LABEL =
%w(NONE SAFE POOR RISKY)

Constants included from Warnings

Warnings::NONE, Warnings::POOR, Warnings::RISKY, Warnings::SAFE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HtmlToPlainText

#convert_to_text, #word_wrap

Constructor Details

#initialize(html, options = {}) ⇒ Premailer

Create a new Premailer object.

html is the HTML data to process. It can be either an IO object, the URL of a remote file, a local path or a raw HTML string. If passing an HTML string you must set the :with_html_string option to true.

Options

line_length

Line length used by to_plain_text. Boolean, default is 65.

warn_level

What level of CSS compatibility warnings to show (see Warnings).

link_query_string

A string to append to every a href="" link. Do not include the initial ?.

base_url

Used to calculate absolute URLs for local files.

css

Manually specify a CSS stylesheet.

css_to_attributes

Copy related CSS attributes into HTML attributes (e.g. background-color to bgcolor)

css_string

Pass CSS as a string

remove_ids

Remove ID attributes whenever possible and convert IDs used as anchors to hashed to avoid collisions in webmail programs. Default is false.

remove_classes

Remove class attributes. Default is false.

remove_comments

Remove html comments. Default is false.

preserve_styles

Whether to preserve any link rel=stylesheet and style elements. Default is false.

with_html_string

Whether the html param should be treated as a raw string.

verbose

Whether to print errors and warnings to $stderr. Default is false.

adapter

Which HTML parser to use, either :nokogiri or :hpricot. Default is :hpricot.



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/premailer/premailer.rb', line 113

def initialize(html, options = {})
  @options = {:warn_level => Warnings::SAFE,
              :line_length => 65,
              :link_query_string => nil,
              :base_url => nil,
              :remove_classes => false,
              :remove_ids => false,
              :remove_comments => false,
              :css => [],
              :css_to_attributes => true,
              :with_html_string => false,
              :css_string => nil,
              :preserve_styles => false,
              :verbose => false,
              :debug => false,
              :io_exceptions => false,
              :adapter => Adapter.use}.merge(options)

  @html_file = html
  @is_local_file = @options[:with_html_string] || Premailer.local_data?(html)

  @css_files = @options[:css]

  @css_warnings = []

  @base_url = nil
  @base_dir = nil
  @unmergable_rules = nil

  if @options[:base_url]
    @base_url = URI.parse(@options.delete(:base_url))
  elsif not @is_local_file
    @base_url = URI.parse(@html_file)
  end

  @css_parser = CssParser::Parser.new({
    :absolute_paths => true,
    :import => true,
    :io_exceptions => @options[:io_exceptions]
  })

  @adapter_name = @options[:adapter]
  @adapter_name, @adapter_class = Adapter.find @adapter_name

  self.class.send(:include, @adapter_class)

  @doc = load_html(@html_file)

  @processed_doc = @doc
  @processed_doc = convert_inline_links(@processed_doc, @base_url) if @base_url
  if options[:link_query_string]
    @processed_doc = append_query_string(@processed_doc, options[:link_query_string])
  end
  load_css_from_options!
  load_css_from_html!
end

Instance Attribute Details

#base_dirObject (readonly)

base directory used to resolve links for local files



71
72
73
# File 'lib/premailer/premailer.rb', line 71

def base_dir
  @base_dir
end

#base_urlObject (readonly)

base URL used to resolve links



68
69
70
# File 'lib/premailer/premailer.rb', line 68

def base_url
  @base_url
end

#docObject (readonly)

source HTML document (Hpricot/Nokogiri)



80
81
82
# File 'lib/premailer/premailer.rb', line 80

def doc
  @doc
end

#html_fileObject (readonly)

URI of the HTML file used



65
66
67
# File 'lib/premailer/premailer.rb', line 65

def html_file
  @html_file
end

#processed_docObject (readonly)

processed HTML document (Hpricot/Nokogiri)



77
78
79
# File 'lib/premailer/premailer.rb', line 77

def processed_doc
  @processed_doc
end

#unmergable_rulesObject (readonly)

unmergeable CSS rules to be preserved in the head (CssParser)



74
75
76
# File 'lib/premailer/premailer.rb', line 74

def unmergable_rules
  @unmergable_rules
end

Class Method Details

.canonicalize(uri) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
# File 'lib/premailer/premailer.rb', line 394

def self.canonicalize(uri) # :nodoc:
u = uri.kind_of?(URI) ? uri : URI.parse(uri.to_s)
u.normalize!
newpath = u.path
while newpath.gsub!(%r{([^/]+)/\.\./?}) { |match|
    $1 == '..' ? match : ''
  } do end
  newpath = newpath.gsub(%r{/\./}, '/').sub(%r{/\.\z}, '/')
  u.path = newpath
  u.to_s
end

.escape_string(str) ⇒ Object

:nodoc:



357
358
359
# File 'lib/premailer/premailer.rb', line 357

def self.escape_string(str) # :nodoc:
  str.gsub(/"/ , "'")
end

.local_data?(data) ⇒ Boolean

Test the passed variable to see if we are in local or remote mode.

IO objects return true, as do strings that look like URLs.

Returns:

  • (Boolean)


383
384
385
386
387
388
389
390
391
# File 'lib/premailer/premailer.rb', line 383

def self.local_data?(data)
  if data.is_a?(IO) || data.is_a?(StringIO)
    return true
  elsif data =~ /^(http|https|ftp)\:\/\//i
    return false
  else
    return true
  end
end

:nodoc:



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/premailer/premailer.rb', line 361

def self.resolve_link(path, base_path) # :nodoc:
  path.strip!
  resolved = nil
  if path =~ /(http[s]?|ftp):\/\//i
    resolved = path
    return Premailer.canonicalize(resolved)
  elsif base_path.kind_of?(URI)
    resolved = base_path.merge(path)
    return Premailer.canonicalize(resolved)
  elsif base_path.kind_of?(String) and base_path =~ /^(http[s]?|ftp):\/\//i
    resolved = URI.parse(base_path)
    resolved = resolved.merge(path)
    return Premailer.canonicalize(resolved)
  else

    return File.expand_path(path, File.dirname(base_path))
  end
end

Instance Method Details

#append_query_string(doc, qs) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/premailer/premailer.rb', line 248

def append_query_string(doc, qs)
  return doc if qs.nil?

  qs.to_s.gsub!(/^[\?]*/, '').strip!
  return doc if qs.empty?

  begin
    current_host = @base_url.host
  rescue
    current_host = nil
  end

  $stderr.puts "Attempting to append_query_string: #{qs}" if @options[:verbose]

  doc.search('a').each do|el|
    href = el.attributes['href'].to_s.strip
    next if href.nil? or href.empty?
    next if href[0,1] == '#' # don't bother with anchors

    begin
      href = URI.parse(href)

      if current_host and href.host != nil and href.host != current_host
        $stderr.puts "Skipping append_query_string for: #{href.to_s} because host is no good" if @options[:verbose]
        next
      end

      if href.scheme and href.scheme != 'http' and href.scheme != 'https'
        puts "Skipping append_query_string for: #{href.to_s} because scheme is no good" if @options[:verbose]
        next
      end

      if href.query and not href.query.empty?
        href.query = href.query + '&' + qs
      else
        href.query = qs
      end

      el['href'] = href.to_s
    rescue URI::Error => e
      $stderr.puts "Skipping append_query_string for: #{href.to_s} (#{e.message})" if @options[:verbose]
      next
    end

  end
  doc
end

#check_client_supportObject

Check CLIENT_SUPPORT_FILE for any CSS warnings



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/premailer/premailer.rb', line 407

def check_client_support # :nodoc:
  @client_support = @client_support ||= YAML::load(File.open(CLIENT_SUPPORT_FILE))

  warnings = []
  properties = []

  # Get a list off CSS properties
  @processed_doc.search("*[@style]").each do |el|
    style_url = el.attributes['style'].to_s.gsub(/([\w\-]+)[\s]*\:/i) do |s|
      properties.push($1)
    end
  end

  properties.uniq!

  property_support = @client_support['css_properties']
  properties.each do |prop|
    if property_support.include?(prop) and
        property_support[prop].include?('support') and
        property_support[prop]['support'] >= @options[:warn_level]
      warnings.push({:message => "#{prop} CSS property",
          :level => WARN_LABEL[property_support[prop]['support']],
          :clients => property_support[prop]['unsupported_in'].join(', ')})
    end
  end

  @client_support['attributes'].each do |attribute, data|
    next unless data['support'] >= @options[:warn_level]
    if @doc.search("*[@#{attribute}]").length > 0
      warnings.push({:message => "#{attribute} HTML attribute",
          :level => WARN_LABEL[data['support']],
          :clients => data['unsupported_in'].join(', ')})
    end
  end

  @client_support['elements'].each do |element, data|
    next unless data['support'] >= @options[:warn_level]
    if @doc.search(element).length > 0
      warnings.push({:message => "#{element} HTML element",
          :level => WARN_LABEL[data['support']],
          :clients => data['unsupported_in'].join(', ')})
    end
  end

  return warnings
end

Processes href src and background attributes as well as CSS url() declarations found in inline style attributes.

doc is an Hpricot document and base_uri is either a string or a URI.

Returns an Hpricot document.



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/premailer/premailer.rb', line 313

def convert_inline_links(doc, base_uri) # :nodoc:
  base_uri = URI.parse(base_uri) unless base_uri.kind_of?(URI)

  append_qs = @options[:link_query_string] || ''

  ['href', 'src', 'background'].each do |attribute|
    tags = doc.search("*[@#{attribute}]")

    next if tags.empty?

    tags.each do |tag|
      # skip links that look like they have merge tags
      # and mailto, ftp, etc...
      if tag.attributes[attribute].to_s =~ /^(\{|\[|<|\#|data:|tel:|file:|sms:|callto:|facetime:|mailto:|ftp:|gopher:)/i
        next
      end

      if tag.attributes[attribute].to_s =~ /^http/i
        begin
          merged = URI.parse(tag.attributes[attribute])
        rescue; next; end
      else
        begin
          merged = Premailer.resolve_link(tag.attributes[attribute].to_s, base_uri)
        rescue
          begin
            merged = Premailer.resolve_link(URI.escape(tag.attributes[attribute].to_s), base_uri)
          rescue; end
        end
      end

      # make sure 'merged' is a URI
      merged = URI.parse(merged.to_s) unless merged.kind_of?(URI)
      tag[attribute] = merged.to_s
    end # end of each tag
  end # end of each attrs

  doc.search("*[@style]").each do |el|
    el['style'] = CssParser.convert_uris(el.attributes['style'].to_s, base_uri)
  end
  doc
end

#is_xhtml?Boolean

Check for an XHTML doctype

Returns:

  • (Boolean)


297
298
299
300
301
302
303
# File 'lib/premailer/premailer.rb', line 297

def is_xhtml?
  intro = @doc.to_s.strip.split("\n")[0..2].join(' ')
  is_xhtml = (intro =~ /w3c\/\/[\s]*dtd[\s]+xhtml/i)
  is_xhtml = is_xhtml ? true : false
  $stderr.puts "Is XHTML? #{is_xhtml.inspect}\nChecked:\n#{intro}" if @options[:debug]
  is_xhtml
end

#local_uri?(uri) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


234
235
236
237
# File 'lib/premailer/premailer.rb', line 234

def local_uri?(uri) # :nodoc:
  warn "[DEPRECATION] `local_uri?` is deprecated.  Please use `Premailer.local_data?` instead."
  Premailer.local_data?(uri)
end

#media_type_ok?(media_types) ⇒ Boolean

here be instance methods

Returns:

  • (Boolean)


241
242
243
244
245
246
# File 'lib/premailer/premailer.rb', line 241

def media_type_ok?(media_types) # :nodoc:
  return true if media_types.nil? or media_types.empty?
  return media_types.split(/[\s]+|,/).any? { |media_type| media_type.strip =~ /screen|handheld|all/i }
rescue
  return true
end

#warningsObject

Array containing a hash of CSS warnings.



171
172
173
174
175
# File 'lib/premailer/premailer.rb', line 171

def warnings
  return [] if @options[:warn_level] == Warnings::NONE
  @css_warnings = check_client_support if @css_warnings.empty?
  @css_warnings
end