Skip to content

Instantly share code, notes, and snippets.

@IronistM
Last active January 26, 2018 16:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IronistM/6697586 to your computer and use it in GitHub Desktop.
Save IronistM/6697586 to your computer and use it in GitHub Desktop.
How to Track Gmail Messages with Google Analytics modified for Universal Analytics tracking. You will need to copy this spreadsheet http://goo.gl/Tk1nR8 and then open Tools > Script Editor to replace the existing code or simply add the /* Universal Analytics Tracking */ part
/*
Email Tracking with Google Analytics
====================================
Written by Amit Agarwal on 09/24/2013
Tutorial: http://labnol.org/?p=8082
YouTube : http://youtu.be/9T_EqwQnZY0
Support : http://twitter.com/labnol
Modified for Universal Analytics tracking
*/
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menu = [
{name: "Initialize", functionName: "reset"},
{name: "Send Mail", functionName: "launch"}
];
ss.addMenu("Email Tracker", menu);
ss.toast("Please click the Email Tracker menu above to continue..", "", 5);
}
function reset() {
return;
}
function launch() {
var threads = GmailApp.search('in:draft', 0, 10);
if (threads.length === 0) {
Browser.msgBox("We found no templates in Gmail. Please write a draft message in your Gmail mailbox to continue.");
return;
}
var myapp = UiApp.createApplication().setTitle('Email Tracker').setHeight(160).setWidth(300);
var top_panel = myapp.createFlowPanel();
top_panel.add(myapp.createLabel("Please select a draft message"));
var lb = myapp.createListBox(false).setWidth(250).setName('templates').addItem("Select draft...").setVisibleItemCount(1);
for (var i = 0; i < threads.length; i++) {
lb.addItem((i+1)+'- '+threads[i].getFirstMessageSubject().substr(0, 40));
}
top_panel.add(lb);
// top_panel.add(myapp.createLabel("").setHeight(10));
// top_panel.add(myapp.createLabel("Please enter your Analytics Profile ID"));
var name_box = myapp.createTextBox().setName("name").setWidth(250);
top_panel.add(name_box);
top_panel.add(myapp.createLabel("").setHeight(5));
var ok_btn = myapp.createButton("Send Mail");
top_panel.add(ok_btn);
myapp.add(top_panel);
var handler = myapp.createServerClickHandler('sendMail').addCallbackElement(lb).addCallbackElement(name_box);
ok_btn.addClickHandler(handler);
SpreadsheetApp.getActiveSpreadsheet().show(myapp);
}
function sendMail(e) {
var draft = GmailApp.search("in:drafts")[(parseInt(e.parameter.templates.substr(0, 2))-1)].getMessages()[0];
var email = draft.getBody();
var attachments = draft.getAttachments();
var to = draft.getTo();
var cc = draft.getCc();
var bcc = draft.getBcc();
var subject = draft.getSubject();
var id = draft.getId();
var regMessageId = new RegExp(id, "g");
if (email.match(regMessageId) != null) {
var inlineImages = {};
var nbrOfImg = email.match(regMessageId).length;
var imgVars = email.match(/<img[^>]+>/g);
var imgToReplace = [];
for (var i = 0; i < imgVars.length; i++) {
if (imgVars[i].search(regMessageId) != -1) {
var id = imgVars[i].match(/Inline\simages?\s(\d)/);
imgToReplace.push([parseInt(id[1]), imgVars[i]]);
}
}
imgToReplace.sort(function (a, b) {
return a[0] - b[0];
});
for (var i = 0; i < imgToReplace.length; i++) {
var attId = (attachments.length - nbrOfImg) + i;
var title = 'inlineImages' + i;
inlineImages[title] = attachments[attId].copyBlob().setName(title);
attachments.splice(attId, 1);
var newImg = imgToReplace[i][1].replace(/src="[^\"]+\"/, "src=\"cid:" + title + "\"");
email = email.replace(imgToReplace[i][1], newImg);
}
}
var trackingGIF = getTrackingGIF(e.parameter.name, to, subject);
email = email + "<img src='" + trackingGIF + "' width='1' height='1'/>";
Logger.log(email)
GmailApp.sendEmail(to, subject, email, {attachments: attachments, htmlBody: email, cc: cc, bcc: bcc, inlineImages: inlineImages});
var app = UiApp.getActiveApplication();
app.close();
return app;
}
function getTrackingGIF(account, email, subject) {
try {
/* Google Analytics Account ID like UA-1234-56 */
/* I will put it in by hand instead of typing all the type */
var utmac = "UA-XXXX-Y";
/* Random ID to prevent browser caching */
var utmn = (Math.round((new Date()).getTime()/1000)).toString();
/* Relative path of the Web Page to be tracked */
// var utmp = "/inbox/" + email.replace("@", ".");
/* Universal Analytics Tracking */
var request_UA = "https://www.google-analytics.com/collect?"
+"v=1" + "&"
+"tid=" + utmac +"&"
+"cid=1" + "&"
+"t=event" + "&"
+"ec=email" + "&"
+"ea=open" + "&"
+"el=" + subject + "&"
+"cs=email" + "&"
+"cm=email" + "&" ;
// +"CD1=" + email; // store the email as a Custom Dimension. BEWARE : Not fine by GA!
return request_UA;
}
catch(e) {
Logger.log(e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment