Skip to content

Instantly share code, notes, and snippets.

@zoernert
Created September 16, 2021 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoernert/b8e13c05a78b9a635b38cc51af30522f to your computer and use it in GitHub Desktop.
Save zoernert/b8e13c05a78b9a635b38cc51af30522f to your computer and use it in GitHub Desktop.
Sendgrid CO2 Offsetting using RapidAPI service
const sendgridAPIKey = 'YOUR_SENDGRID_API_KEY';
const rapidAPIKey = 'YOUR_RAPIDAPI_KEY';
const fromDate = new Date(new Date().getTime() - (7*87600000)).toISOString().split('T')[0]; // last 7 days
const axios = require("axios");
// Retrieve Statistics from Sendgrid
const sendgridStatsResponds = await axios.get("https://sendgrid.com/v3/stats?start_date="+fromDate,{
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer '+sendgridAPIKey
}
});
const mailStats = sendgridStatsResponds.data;
// Calculate co2 emission based on stats
let totalco2 = 0;
for(let i=0;i<mailStats.length;i++) {
for(let j=0;j<mailStats[i].stats.length;j++) {
for (const [key, value] of Object.entries(mailStats[i].stats[j].metrics)) {
if(key == "blocks") totalco2+=1
if(key == "bounce_drops") totalco2+=2
if(key == "bounces") totalco2+=2
if(key == "clicks") totalco2+=2
if(key == "deferred") totalco2+=2
if(key == "delivered") totalco2+=20
if(key == "invalid_emails") totalco2+=0
if(key == "opens") totalco2+=10
if(key == "processed") totalco2+=15
if(key == "requests") totalco2+=0
if(key == "spam_report_drops") totalco2+=1
if(key == "spam_reports") totalco2+=3
if(key == "unique_clicks") totalco2+=5
if(key == "unique_opens") totalco2+=5
if(key == "unsubscribe_drops") totalco2+=0
if(key == "unsubscribes") totalco2+=2
}
}
}
// Run Compensation via RapidAPI Call
const options = {
method: 'GET',
url: 'https://co2-offset.p.rapidapi.com/rapidapi/compensate',
params: {gram: totalco2},
headers: {
'x-rapidapi-host': 'co2-offset.p.rapidapi.com',
'x-rapidapi-key': rapidAPIKey
}
};
const compensationCall = await axios.request(options);
console.log('Your CO2 Compensation Certificate for '+totalco2+'g ',compensationCall.data.certificate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment