Skip to content

Instantly share code, notes, and snippets.

@adminy
Last active November 29, 2021 14:07
Show Gist options
  • Save adminy/1c7e38f1f0e7bdeceece5107a5954604 to your computer and use it in GitHub Desktop.
Save adminy/1c7e38f1f0e7bdeceece5107a5954604 to your computer and use it in GitHub Desktop.
Google drive Download Entire Gmail Stack
const getMessage = message => Utilities.newBlob(message.getRawContent(), null, `${['Id', 'Subject', 'Date'].map(action => message['get' + action]()).join('_')}.eml`)
const getThread = thread => Utilities.zip(thread.getMessages().map(message => getMessage(message)), thread.getId() + '_' + thread.getFirstMessageSubject() + '.zip')
const getInbox = label => GmailApp.search(label).map(thread => getThread(thread))
const labels = GmailApp.getUserLabels().map(label => 'label:' + label.getName())
const emails = ['in:sent', 'in:inbox', ...labels].map(label => Utilities.zip(getInbox(label), label + '.zip'))
DriveApp.createFile(Utilities.zip(emails, 'emails.zip'))
@adminy
Copy link
Author

adminy commented Nov 29, 2021

Perhaps instead of zips, its wiser to figure out how Mbox format works, so that its easier to import the emails.

@adminy
Copy link
Author

adminy commented Nov 29, 2021

Here is a gist for sorting your mails into the right labels:

const fromTo = {
  'no-reply@dropbox.com': 'tools',
  'feedback@slack.com': 'tools',
  'drive-shares-dm-noreply@google.com': 'tools',
  '@am.atlassian.com': 'tools',
  'atlassian.net': 'tools',
  '@expensify.com': 'money',
  'noreply@parolla.ie': 'money'
}

const senderTo = {
  'google': 'calendar',
  'expensify': 'money'
}

function moveTo (thread, label) {
  thread.addLabel(GmailApp.getUserLabelByName(label))
  thread.moveToArchive()
  console.log(label, ' → ', thread.getFirstMessageSubject())
} 

function checkSender (thread, sender) {
    for (const name in senderTo) {
      sender.includes(name) && moveTo(thread, senderTo[name])
    }
}

function checkPeople (thread, messages) {
    const people = [...new Set(messages.map(msg => [msg.getFrom(), msg.getCc(), msg.getBcc()]).flat().filter(x => x))]
    for (const from in fromTo) {
      people.some(person => person.includes(from)) && moveTo(thread, fromTo[from])
    }
}

function emailSorter() {
  const inbox = GmailApp.getInboxThreads()
  for (const thread of inbox) {  
    const messages = thread.getMessages()
    const sender = messages[0].getHeader('Sender')
    sender ? checkSender(thread, sender) : checkPeople(thread, messages)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment