Open DevCEDTeam opened 1 year ago
To create an image pixel for email tracking, you can follow these instructions:
Step 1: Set up a Google Cloud Project
Step 2: Enable the necessary APIs
Step 3: Create a Cloud Storage bucket
Step 4: Write the Cloud Function code
emailTracking.js
) with the following code:const { Storage } = require('@google-cloud/storage');
const crypto = require('crypto');
const storage = new Storage();
exports.trackEmailOpen = (req, res) => {
const trackingCode = generateTrackingCode();
const bucketName = 'your-bucket-name'; // Replace with your Cloud Storage bucket name
const fileName = `${trackingCode}.png`;
const file = storage.bucket(bucketName).file(fileName);
const stream = file.createWriteStream({
resumable: false,
contentType: 'image/png',
public: true,
metadata: {
metadata: {
trackingCode: trackingCode
}
}
});
stream.end(Buffer.from([]));
res.status(200).send(trackingCode);
};
function generateTrackingCode() {
const codeLength = 12;
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let code = '';
for (let i = 0; i < codeLength; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
code += characters.charAt(randomIndex);
}
return code;
}
Make sure to replace 'your-bucket-name'
with the name of the Cloud Storage bucket you created in Step 3.
Step 5: Deploy the Cloud Function
emailTracking.js
file.gcloud functions deploy trackEmailOpen --runtime nodejs14 --trigger-http --allow-unauthenticated
This command deploys the trackEmailOpen
function as an HTTP-triggered Cloud Function and allows unauthenticated access to it. Adjust the options as per your requirements.
Step 6: Obtain the tracking URL
https://REGION-PROJECT_ID.cloudfunctions.net/trackEmailOpen
).Step 7: Insert the tracking pixel in your email template
<img>
tag with the src
attribute set to the tracking pixel URL obtained in Step 6.<img src="https://REGION-PROJECT_ID.cloudfunctions.net/trackEmailOpen" alt="Email Tracking Pixel" width="1" height="1">
.Step 8: Track email opens
To complete the step of tracking email opens, you can modify the Cloud Function code to integrate with Google Analytics. Here's an example of how you can achieve this:
const { Storage } = require('@google-cloud/storage');
const crypto = require('crypto');
const uaParser = require('ua-parser-js');
const { google } = require('googleapis');
const storage = new Storage();
exports.trackEmailOpen = async (req, res) => {
const trackingCode = generateTrackingCode();
const bucketName = 'your-bucket-name'; // Replace with your Cloud Storage bucket name
const fileName = `${trackingCode}.png`;
const file = storage.bucket(bucketName).file(fileName);
const stream = file.createWriteStream({
resumable: false,
contentType: 'image/png',
public: true,
metadata: {
metadata: {
trackingCode: trackingCode
}
}
});
stream.end(Buffer.from([]));
// Track the email open event in Google Analytics
const ua = uaParser(req.headers['user-agent']);
const client = await google.analytics('v3');
const analyticsParams = {
v: '1', // API version
tid: 'UA-XXXXXXXXX-X', // Replace with your Google Analytics tracking ID
cid: trackingCode, // Use the tracking code as the client ID
t: 'event', // Event hit type
ec: 'Email', // Event category
ea: 'Open', // Event action
el: 'Email Open', // Event label
ua: `${ua.browser.name} ${ua.browser.version}`, // User agent
dr: req.query.referrer || '', // Referrer
uip: req.ip // IP address
};
await client.data.ga.send(analyticsParams);
res.status(200).send(trackingCode);
};
function generateTrackingCode() {
const codeLength = 12;
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let code = '';
for (let i = 0; i < codeLength; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
code += characters.charAt(randomIndex);
}
return code;
}
In the code above, we've made the following changes:
ua-parser-js
package to parse the user agent header and extract browser details.googleapis
package to interact with the Google Analytics API.trackEmailOpen
function to handle email open events.'UA-XXXXXXXXX-X'
with your actual Google Analytics tracking ID.req.query.referrer
) if provided.ua.browser.name
and ua.browser.version
) and IP address (req.ip
) in the Google Analytics event parameters.With these modifications, the Cloud Function will not only create the image pixel in Cloud Storage but also track email opens using Google Analytics.
Remember to redeploy the Cloud Function with the updated code using the gcloud functions deploy
command.
NA