forked from x4nth055/pythoncode-tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
Latest commit
43 lines (38 loc) · 1.69 KB
/
Copy pathcommon.py
File metadata and controls
43 lines (38 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
importos
importpickle
# Gmail API utils
fromgoogleapiclient.discoveryimportbuild
fromgoogle_auth_oauthlib.flowimportInstalledAppFlow
fromgoogle.auth.transport.requestsimportRequest
# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES= ['https://mail.google.com/']
our_email='our_email@gmail.com'
defgmail_authenticate():
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
ifos.path.exists("token.pickle"):
withopen("token.pickle", "rb") astoken:
creds=pickle.load(token)
# if there are no (valid) credentials availablle, let the user log in.
ifnotcredsornotcreds.valid:
ifcredsandcreds.expiredandcreds.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
withopen("token.pickle", "wb") astoken:
pickle.dump(creds, token)
returnbuild('gmail', 'v1', credentials=creds)
defsearch_messages(service, query):
result=service.users().messages().list(userId='me',q=query).execute()
messages= [ ]
if'messages'inresult:
messages.extend(result['messages'])
while'nextPageToken'inresult:
page_token=result['nextPageToken']
result=service.users().messages().list(userId='me',q=query, pageToken=page_token).execute()
if'messages'inresult:
messages.extend(result['messages'])
returnmessages