How to classify your emails with Gmail, labels and AI
Automatically categorize incoming emails using AI and label them in Gmail.
Your task is to classify incoming emails into one of the following categories:
- Newsletter
- Order
- Shipping
- Public Event
- Personal Event
- Personal
- Advertising
- Other
Return only the category name without additional explanation or quotation marks.
//exec:node
const labelsToCreate = [
"Newsletter", "Order", "Shipping", "Public Event", "Personal Event", "Personal", "Advertising", "Other"
];
// Create labels and get their IDs
const labels = await createAndGetLabels(labelsToCreate);
print(labels)
const google = await getGoogleClient();
const gmail = google.gmail({ version: 'v1' });
const promptSystem = loadBlock('prompt');
const res = await gmail.users.messages.list({
userId: 'me',
labelIds: ['INBOX'],
maxResults: 10
});
if (res.data.messages) {
for (const message of res.data.messages) {
const msg = await gmail.users.messages.get({
userId: 'me',
id: message.id
});
const mail = readGmailMail(msg.data);
const finalPrompt = `
${promptSystem}
Here is the email to classify:
Date: ${mail.Date}
From: ${mail.From}
To: ${mail.To}
Subject: ${mail.Subject}
`;
const deducedLabel = await useLocalAI("mistral", false, finalPrompt);
// Ensure AI response is a valid category
if (deducedLabel && labels.has(deducedLabel.trim())) {
const labelId = labels.get(deducedLabel.trim());
print(`✅ Classified: ${deducedLabel.trim()} => ${mail.From} | ${mail.Subject}`);
/*
await gmail.users.messages.modify({
userId: 'me',
id: mail.id,
requestBody: {
// addLabelIds: [labelId], // Uncomment when ready to apply labels
// removeLabelIds: ["INBOX"], // Uncomment to move emails out of the inbox
},
});
*/
} else {
print(`⚠️ No valid label found: ${deducedLabel.trim()} | ${mail.From} | ${mail.Subject}`);
}
}
}
🔗 More Info: Node.js Gmail API Docs 🚀