|
| 1 | +"""Copyright 2018 Google LLC |
| 2 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +you may not use this file except in compliance with the License. |
| 4 | +You may obtain a copy of the License at |
| 5 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +Unless required by applicable law or agreed to in writing, software |
| 7 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +See the License for the specific language governing permissions and |
| 10 | +limitations under the License. |
| 11 | +""" |
| 12 | +# [START gmail_show_chatty_threads] |
| 13 | + |
| 14 | +from __future__ import print_function |
| 15 | + |
| 16 | +import google.auth |
| 17 | +from googleapiclient.discovery import build |
| 18 | +from googleapiclient.errors import HttpError |
| 19 | + |
| 20 | + |
| 21 | +def show_chatty_threads(): |
| 22 | + """Display threads with long conversations(>= 3 messages) |
| 23 | + Return: None |
| 24 | +
|
| 25 | + Load pre-authorized user credentials from the environment. |
| 26 | + TODO(developer) - See https://developers.google.com/identity |
| 27 | + for guides on implementing OAuth2 for the application. |
| 28 | + """ |
| 29 | + creds, _ = google.auth.default() |
| 30 | + |
| 31 | + try: |
| 32 | + # create gmail api client |
| 33 | + service = build('gmail', 'v1', credentials=creds) |
| 34 | + |
| 35 | + # pylint: disable=maybe-no-member |
| 36 | + threads = service.users().threads().list(userId='me').execute().get('threads', []) |
| 37 | + for thread in threads: |
| 38 | + tdata = service.users().threads().get(userId='me', id=thread['id']).execute() |
| 39 | + nmsgs = len(tdata['messages']) |
| 40 | + |
| 41 | + # skip if <3 msgs in thread |
| 42 | + if nmsgs > 2: |
| 43 | + msg = tdata['messages'][0]['payload'] |
| 44 | + subject = '' |
| 45 | + for header in msg['headers']: |
| 46 | + if header['name'] == 'Subject': |
| 47 | + subject = header['value'] |
| 48 | + break |
| 49 | + if subject: # skip if no Subject line |
| 50 | + print(F'- {subject}, {nmsgs}') |
| 51 | + |
| 52 | + except HttpError as error: |
| 53 | + print(F'An error occurred: {error}') |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + show_chatty_threads() |
| 58 | +# [END gmail_show_chatty_threads] |
0 commit comments