Skip to content

Instantly share code, notes, and snippets.

@kjoconnor
Created January 23, 2020 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjoconnor/b98cc237536f05dd444f0eb69ff14d64 to your computer and use it in GitHub Desktop.
Save kjoconnor/b98cc237536f05dd444f0eb69ff14d64 to your computer and use it in GitHub Desktop.
I used this script to delete a bunch of cron emails that had built up in my inbox. You should be able to change the search params to cover anything you might want to get rid of. Note this will _permanently delete_, not just move to trash.
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://mail.google.com/']
def _update_creds():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def clean_crons(next_page_token=None, deleted_count=0):
creds = _update_creds()
service = build('gmail', 'v1', credentials=creds)
if next_page_token:
results = service.users().threads().list(
userId='me',
q='label:cron',
pageToken=next_page_token,
).execute()
else:
results = service.users().threads().list(
userId='me',
q='label:cron',
).execute()
threads = results.get('threads')
if threads:
for thread in threads:
print('deleting %s' % thread['id'])
service.users().threads().delete(
userId='me',
id=thread['id'],
).execute()
deleted_count += len(threads)
print('deleted %s so far' % deleted_count)
else:
print('done at %s' % deleted_count)
return
next_page_token = results.get('nextPageToken')
if next_page_token:
clean_crons(
next_page_token=next_page_token,
deleted_count=deleted_count,
)
if __name__ == '__main__':
clean_crons()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment