Skip to content

Instantly share code, notes, and snippets.

@TownLake
Created January 27, 2025 15:33
Show Gist options
  • Save TownLake/b355e6c000f4d6482522fe4d9a41d450 to your computer and use it in GitHub Desktop.
Save TownLake/b355e6c000f4d6482522fe4d9a41d450 to your computer and use it in GitHub Desktop.
multi-label-summary
function forwardLabeledEmails() {
const labels = ["label1", "label2", "label3"]; // Multiple labels
const workerEndpoint = "";
const authToken = "";
const recipientEmail = ""; // Replace with your email address
// Get the date 24 hours ago
const now = new Date();
const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
// Format the date for Gmail search (yyyy/MM/dd)
const formattedDate = Utilities.formatDate(twentyFourHoursAgo, Session.getScriptTimeZone(), "yyyy/MM/dd");
// Initialize an empty array to store all email threads
let allThreads = [];
// Loop over each label and fetch the emails
labels.forEach(label => {
const searchQuery = `label:${label} after:${formattedDate}`;
const threads = GmailApp.search(searchQuery);
if (threads.length === 0) {
Logger.log(`No emails found with the label "${label}" in the last 24 hours.`);
} else {
allThreads = allThreads.concat(threads); // Combine threads from all labels
}
});
if (allThreads.length === 0) {
Logger.log("No emails found with the specified labels in the last 24 hours.");
return;
}
const emailsToSend = allThreads.map(thread => {
const messages = thread.getMessages();
return messages.map(message => ({
subject: message.getSubject(),
from: message.getFrom(),
body: message.getPlainBody(),
}));
}).flat();
// Prepare the request payload
const payload = {
messages: [
{
role: "system",
content: "Summarize these emails. Highlight any important or urgent details.",
},
{
role: "user",
content: formatEmailContent(emailsToSend),
},
],
};
// Send the payload to the Cloudflare Workers endpoint and handle the response
const response = sendToWorker(workerEndpoint, payload, authToken);
if (response) {
sendEmailWithSummary(recipientEmail, response);
} else {
Logger.log("No response received from the Cloudflare Workers endpoint.");
}
}
function formatEmailContent(emails) {
// Format the emails as a readable string
return emails.map(email => {
return `From: ${email.from}\nSubject: ${email.subject}\nBody: ${email.body}\n\n`;
}).join("\n");
}
function sendToWorker(endpoint, payload, authToken) {
const options = {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload),
headers: {
Authorization: `Bearer ${authToken}`, // Include Bearer token in the header
"Content-Type": "application/json", // Explicitly set content type
},
muteHttpExceptions: true, // This allows us to see the full response if an error occurs
};
try {
const response = UrlFetchApp.fetch(endpoint, options);
const responseCode = response.getResponseCode();
const responseText = response.getContentText();
Logger.log(`Response Code: ${responseCode}`);
Logger.log(`Response Body: ${responseText}`);
if (responseCode === 200) {
return JSON.parse(responseText);
} else {
throw new Error(`Failed to send payload. Response: ${responseText}`);
}
} catch (error) {
Logger.log(`Error sending payload: ${error.message}`);
return null;
}
}
function sendEmailWithSummary(recipient, summary) {
// Extract the summary response from Cloudflare Workers AI
const summaryContent = summary?.result?.response || "No summary available.";
// Construct the email content
const subject = "Summary of Recent Emails";
const body = `Here is the summary generated by Cloudflare Workers AI:\n\n${summaryContent}`;
try {
GmailApp.sendEmail(recipient, subject, body);
Logger.log(`Summary email sent to ${recipient}`);
} catch (error) {
Logger.log(`Error sending email: ${error.message}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment