Rsnarsna commited on
Commit
29aa16a
·
verified ·
1 Parent(s): 4c00a7a

Upload 2 files

Browse files
Files changed (2) hide show
  1. Credentials.json +1 -0
  2. mailauto_googleapi.py +86 -0
Credentials.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"installed":{"client_id":"469525949579-fgsfredb59mctdm6lrgeqmh8s8rcigsp.apps.googleusercontent.com","project_id":"leafy-acumen-357008","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
mailauto_googleapi.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+ import base64
3
+ import json
4
+ import pickle
5
+ from google.auth.transport.requests import Request
6
+ from google.oauth2.credentials import Credentials
7
+ from google_auth_oauthlib.flow import InstalledAppFlow
8
+ from googleapiclient.discovery import build
9
+ from googleapiclient.errors import HttpError
10
+
11
+ # If modifying these SCOPES, delete the file token.json.
12
+ SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
13
+
14
+ def authenticate_gmail():
15
+ """Shows basic usage of the Gmail API.
16
+ Lists the user's Gmail labels.
17
+ """
18
+ creds = None
19
+ # The file token.json stores the user's access and refresh tokens, and is
20
+ # created automatically when the authorization flow completes for the first time.
21
+ if os.path.exists('token.json'):
22
+ creds = Credentials.from_authorized_user_file('token.json', SCOPES)
23
+ # If there are no (valid) credentials available, let the user log in.
24
+ if not creds or not creds.valid:
25
+ if creds and creds.expired and creds.refresh_token:
26
+ creds.refresh(Request())
27
+ else:
28
+ flow = InstalledAppFlow.from_client_secrets_file(
29
+ 'Credentials.json', SCOPES)
30
+ creds = flow.run_local_server(port=0)
31
+ # Save the credentials for the next run
32
+ with open('token.json', 'w') as token:
33
+ token.write(creds.to_json())
34
+
35
+ try:
36
+ # Call the Gmail API
37
+ service = build('gmail', 'v1', credentials=creds)
38
+ return service
39
+ except HttpError as error:
40
+ print(f'An error occurred: {error}')
41
+ return None
42
+
43
+ def get_latest_email(service):
44
+ """Get the latest email from the inbox"""
45
+ try:
46
+ # Retrieve a list of messages
47
+ results = service.users().messages().list(userId='me', maxResults=1).execute()
48
+ messages = results.get('messages', [])
49
+
50
+ if not messages:
51
+ print('No messages found.')
52
+ return
53
+
54
+ # Get the message ID
55
+ message_id = messages[0]['id']
56
+
57
+ # Fetch the email content by message ID
58
+ message = service.users().messages().get(userId='me', id=message_id, format='full').execute()
59
+
60
+ # Get the email payload
61
+ payload = message['payload']
62
+ headers = payload.get('headers', [])
63
+
64
+ # Print the sender, subject, and body of the email
65
+ for header in headers:
66
+ if header['name'] == 'From':
67
+ print(f"From: {header['value']}")
68
+ if header['name'] == 'Subject':
69
+ print(f"Subject: {header['value']}")
70
+
71
+ # Extract the body
72
+ parts = payload.get('parts', [])
73
+ for part in parts:
74
+ if part.get('mimeType') == 'text/plain':
75
+ body = part.get('body', {}).get('data', '')
76
+ body_decoded = base64.urlsafe_b64decode(body).decode('utf-8')
77
+ print(f"Body: {body_decoded}")
78
+
79
+ except HttpError as error:
80
+ print(f'An error occurred: {error}')
81
+
82
+ if __name__ == '__main__':
83
+ service = authenticate_gmail()
84
+ print(service)
85
+ if service:
86
+ get_latest_email(service)