Skip to content

Instantly share code, notes, and snippets.

@evenv
Created December 25, 2014 21:59
Show Gist options
  • Save evenv/bede6717c28321618f52 to your computer and use it in GitHub Desktop.
Save evenv/bede6717c28321618f52 to your computer and use it in GitHub Desktop.
add labels in gmail based on email info
import os, os.path, re
import httplib2
from email.Header import decode_header
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
print
print "##############################################################################################"
print
CLIENT_SECRET_FILE = 'client_secret.json'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.modify'
STORAGE = Storage('gmail.storage')
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run(flow, STORAGE, http=http)
http = credentials.authorize(http)
gmail_service = build('gmail', 'v1', http=http)
######
# Legge opp alle GMail-labels i en dict
label_res = gmail_service.users().labels().list(userId='me').execute()
labels = {}
for label in label_res['labels']:
labels[label['name']] = label['id']
# Scanne gjennom alle filer
dirtocheck = "~/Library/Mail/V2/Mailboxes"
goodboxes = []
i = 0
STOP = 20000
done_roots = []
for root, _, files in os.walk(dirtocheck):
print "Root:", root
root_is_done = False
for done_root in done_roots:
if root.find(done_root) != -1:
root_is_done = True
if root_is_done:
print "Skipped"
continue
for filename in files:
if filename.find(".emlx") != -1:
try:
i=i+1
if i>STOP:
break
fullpath = os.path.join(root, filename)
print
print fullpath
boxes = re.findall(r'([^/]+)\.mbox', fullpath)
label = '/'.join(boxes)
if not label in labels:
print "WARN: Fant ikke labelen... Hopper over"
continue
f = open(fullpath,'r')
subject = re.findall(r'Subject: (.*)', f.read())
f.close()
subject = subject[0]
if '?iso-8859-1' in subject:
he = decode_header(subject)
subject = he[0][0]
f = open(fullpath,'r')
sender = re.findall(r'From: (.*)', f.read())
f.close()
sender = sender[0]
if '<' in sender:
sender = re.findall(r'.*<(.*)>.*', sender)[0]
f = open(fullpath,'r')
recipient = re.findall(r'To: (.*)', f.read())
f.close()
recipient = recipient[0]
if '<' in recipient:
recipient = re.findall(r'.*<(.*)>.*', recipient)[0]
f = open(fullpath,'r')
msgid = re.findall(r'Message-I(D|d): <(.*)>', f.read())
f.close()
msgid = msgid[0][1]
labelid = labels[label]
print "Sender:", sender
print "Recipient:", recipient
print "Subject:", subject
print "Message-Id:", msgid
print "Label:", label, "--", labelid
query = "from:\"%s\" to:\"%s\" rfc822msgid:\"%s\"" % (sender, recipient, msgid)
hits = gmail_service.users().messages().list(userId='me', q=query).execute()
if 'messages' not in hits.keys():
print "WARN: Ingen treff"
else:
for hit in hits['messages']:
print "GMail ID:", hit['id']
hitmsg = gmail_service.users().messages().get( userId = 'me', id = hit['id'] ).execute()
for header in hitmsg['payload']['headers']:
if header['name'] == 'From':
print "GMail From:", header['value']
if header['name'] == "To":
print "GMail To:", header['value']
if header['name'] == "Subject":
print "GMail Subject:", header['value']
if header['name'] == "Message-Id" or header['name'] == 'Message-ID':
print "GMail Message-ID:", header['value']
res = gmail_service.users().messages().modify(userId = 'me', id = hit['id'], body = {"addLabelIds":[labelid]}).execute()
except:
pass
###########
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment