Skip to content

Instantly share code, notes, and snippets.

@wangzuo
Last active December 6, 2016 06:41
Show Gist options
  • Save wangzuo/2bf8d8ed15793e4a06fc9e807aad742c to your computer and use it in GitHub Desktop.
Save wangzuo/2bf8d8ed15793e4a06fc9e807aad742c to your computer and use it in GitHub Desktop.

Rails mailer guide

Notice

  • email styling is hard outlook-margins
  • url helper
  • config.action_mailer.asset_host
  • assets:precompile on sidekiq server
  • <img alt="" /> with image disabled by default
  • encrypt helper for token

Inline styles

  • <style> removed by different email clients
  • premailer
  • Premailer.new('<style>p { font-size: 11px; }</style><p>hello world</p>', with_html_string: true).to_inline_css
  • after_action: premailer
  • mailer/index.scss
  • @retain_style for extra <style types="text/css">...</style> (media query)
  • hack
def premailer
  if Rails.env.production?
    css_path = Rails.application.assets_manifest.assets['mailer/index.css']
    styles = File.open("#{Rails.root}/public/assets/#{css_path}", 'r').read
  else
    styles = Athena::Application.assets.find_asset('mailer/index.scss').source
  end

  if message.parts.empty?
    html = message.body.raw_source.to_str
  else
    html = message.html_part.body.raw_source.to_str
  end

  premailer = Premailer.new("<style>#{styles}</style>#{html}", with_html_string: true)
  output = premailer.to_inline_css
  output = output.gsub(%r{<style(.*)<\/style>}m, '') unless @retain_style

  part = Mail::Part.new(
    content_type: 'text/html; charset=utf-8',
    body: output
  )

  if message.parts.empty?
    message.body = part.decoded
  else
    message.html_part.body = part.decoded
  end
end

Foundation for Emails

Email testing

Cleanup

  • layout/mailer.html.erb, layout/meeting_mailer.html.erb
  • gem 'foundation_emails'

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment