Skip to content

Instantly share code, notes, and snippets.

@TownLake
Created January 17, 2025 17:06
Show Gist options
  • Save TownLake/765ff92cb50a17105fb7b71727c137f5 to your computer and use it in GitHub Desktop.
Save TownLake/765ff92cb50a17105fb7b71727c137f5 to your computer and use it in GitHub Desktop.
function forwardLabeledEmails() {
const labelName = "";
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");
// Search for emails with the specified label received after the formatted date
const searchQuery = `label:${labelName} after:${formattedDate}`;
const threads = GmailApp.search(searchQuery);
if (threads.length === 0) {
Logger.log(`No emails found with the label "${labelName}" in the last 24 hours.`);
return;
}
const emailsToSend = threads.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