Znote (recipes)
  Get Znote  

Gmail classification

How to classify your emails with Gmail, labels and AI

 

Gmail classification

👉 Insure you follow the Google API initialization and install the Ollama plugin

Prompt

Your role is to determine the category of the emails received by choosing from the categories listed below.

Here are the possible categories:
- Newsletter
- Order
- Shipping
- Public Event
- Personal Event
- Personal
- Advertising
- Other

You must return in response the name of the category without further explanation and without quotation marks.

Read mails

//exec:node
const labelsToCreate = [
  "Newsletter", "Order", "Shipping", "Public Event", "Personal Event", "Personal", "Advertising", "Other"
]

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) {
  const messages = res.data.messages;
  
  for (const message of messages) {
    const msg = await gmail.users.messages.get({
      userId: 'me',
      id: message.id
    });
    //printJSON(msg.data)
    
    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);
    
    // Ensures that the AI ​​returned a valid response
    if (deducedLabel && labels.has(deducedLabel.trim())) {
        const labelId = labels.get(deducedLabel.trim());
        
        print(`Add label: ${deducedLabel.trim()} => ${mail.From} ${mail.Subject}`)
      
        const res = await gmail.users.messages.modify({
          userId: 'me',
          id: mail.id,
          requestBody: {
            //addLabelIds: [labelId], // <<- Uncomment when you are ready with your prompt
            //removeLabelIds: ["INBOX"], // to remove message from your inbox
          },
        });
  
    } else {
      print(`No label found for: ${result.trim()} ${mail.From} : ${mail.Subject}`)
    }
  
  }
}

More info about the API 👉 NodeJs Gmail API

Related recipes