This gist illustrates how you would add Google Analytics tracking into your Rails mailers. Add the tracking_interceptor.rb
into your path and enable it for your mailers with:
register_interceptor TrackingInterceptor
This gist illustrates how you would add Google Analytics tracking into your Rails mailers. Add the tracking_interceptor.rb
into your path and enable it for your mailers with:
register_interceptor TrackingInterceptor
class TrackingInterceptor | |
def self.delivering_email(email) | |
if email.html_part | |
ERB::Util.url_encode | |
# Open Tracking | |
# @see http://dyn.com/blog/tracking-email-opens-via-google-analytics/ | |
tracking_img = '<img src="http://www.google-analytics.com/collect?v=1' | |
tracking_img << '&tid=' + Rails.application.config.ga_account_id # Analytics tracking ID | |
tracking_img << '&cid=' + email.to.first.hash.to_s # Id identifying user, but need to not be personally identifying | |
tracking_img << '&t=event' # Tells Google Analytics this is an Event Hit Type | |
tracking_img << '&ec=Email' # The Event Category helps segment various events | |
tracking_img << '&ea=Open' # The Event Action helps specify exactly what happened | |
tracking_img << '&el=' + ERB::Util.url_encode label # Event Label specifies a unique identification for this event | |
tracking_img << '&cs=' + ERB::Util.url_encode campaign_source # Campaign Source allows segmentation of campaign types | |
tracking_img << '&cm=email' # Campaign Medium could segment social vs. email, etc. | |
tracking_img << '&cn=' + ERB::Util.url_encode capaign_name # Campaign Name identifies the campaign to you | |
tracking_img << '" />' | |
email.html_part.body.raw_source.gsub!(/(?=<\/body>)/, tracking_img.html_safe) # Assumes that the email has proper body tags | |
# Click Tracking | |
# @see http://www.smartinsights.com/email-marketing/email-marketing-analytics/email-campaign-tracking-with-google-analytics/ | |
tracking_params = "utm_medium=email&utm_campaign=#{ERB::Util.url_encode capaign_name}&utm_source=#{ERB::Util.url_encode campaign_source}" | |
email.html_part.body.raw_source.gsub!(/href=".+?(?=")/) do |link| | |
if link =~ /\?/ | |
link + '&' + tracking_params | |
else | |
link + '?' + tracking_params | |
end | |
end | |
end | |
end | |
end | |
My take