Gnome SHELL Generic Monitor

Gnome SHELL Generic Monitor Git Source Tree

Root/examples/gmail.py

1#
2# Copyright 2018 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16#
17# Setup : https://developers.google.com/gmail/api/quickstart/python
18# Need to have credentials.json were you call main script
19#
20# File imported from https://github.com/googleworkspace/python-samples/blob/main/gmail/quickstart/quickstart.py
21#
22
23from __future__ import print_function
24
25import os.path
26
27from google.auth.transport.requests import Request
28from google.oauth2.credentials import Credentials
29from google_auth_oauthlib.flow import InstalledAppFlow
30from googleapiclient.discovery import build
31
32# If modifying these scopes, delete the file token.json.
33SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
34
35creds = None
36
37def _initCreds():
38 global creds
39 if creds: return
40
41 # The file token.json stores the user's access and refresh tokens, and is
42 # created automatically when the authorization flow completes for the first
43 # time.
44 if os.path.exists('token.json'):
45 creds = Credentials.from_authorized_user_file('./token.json', SCOPES)
46 # If there are no (valid) credentials available, let the user log in.
47 if not creds or not creds.valid:
48 if creds and creds.expired and creds.refresh_token:
49 creds.refresh(Request())
50 else:
51 flow = InstalledAppFlow.from_client_secrets_file(
52 'credentials.json', SCOPES)
53 creds = flow.run_local_server(port=0)
54 # Save the credentials for the next run
55 with open('token.json', 'w') as token:
56 token.write(creds.to_json())
57
58def getUnreadMails():
59 """
60 Get number of unread threads (that may contain multiple messages)
61 """
62
63 _initCreds()
64
65 service = build('gmail', 'v1', credentials=creds)
66 pageToken = ''
67 threads = set()
68 while True:
69 results = service.users().messages().list(userId='me', labelIds=['UNREAD'],\
70 includeSpamTrash=False, pageToken=pageToken)\
71 .execute()
72 threads = threads.union(set([k['threadId'] for k in results['messages']]))
73 # Loop over all result pages (100 results per page by default)
74 pageToken = results.get('nextPageToken', '')
75 if not pageToken: break
76
77 return len(threads)

Archive Download this file

Branches

Tags