wahab5763 commited on
Commit
160f1c7
·
verified ·
1 Parent(s): 73f075b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -70
app.py CHANGED
@@ -28,8 +28,8 @@ def authenticate_gmail(credentials_file):
28
  if creds and creds.valid:
29
  st.session_state.creds = creds
30
  st.session_state.authenticated = True
31
- fetch_emails_directly()
32
- return
33
  except Exception as e:
34
  st.error(f"Invalid token.json file: {e}")
35
  os.remove('token.json')
@@ -38,8 +38,8 @@ def authenticate_gmail(credentials_file):
38
  if st.session_state.creds and st.session_state.creds.expired and st.session_state.creds.refresh_token:
39
  st.session_state.creds.refresh(Request())
40
  st.session_state.authenticated = True
41
- fetch_emails_directly()
42
- return
43
  else:
44
  if not st.session_state.flow:
45
  st.session_state.flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
@@ -56,7 +56,6 @@ def authenticate_gmail(credentials_file):
56
  st.session_state.flow.fetch_token(code=auth_code)
57
  st.session_state.creds = st.session_state.flow.credentials
58
  st.session_state.authenticated = True
59
- # Save the credentials to a file for later use
60
  with open('token.json', 'w') as token_file:
61
  json.dump({
62
  "token": st.session_state.creds.token,
@@ -66,70 +65,37 @@ def authenticate_gmail(credentials_file):
66
  "client_secret": st.session_state.creds.client_secret,
67
  "scopes": st.session_state.creds.scopes
68
  }, token_file)
69
- st.success("Authentication successful! Fetching emails...")
70
- fetch_emails_directly()
71
  except Exception as e:
72
  st.error(f"Error during authentication: {e}")
73
 
74
- def fetch_emails_directly():
75
- if st.session_state.authenticated and st.session_state.creds:
76
- service = build('gmail', 'v1', credentials=st.session_state.creds)
77
- label = "INBOX" # Default label, you can make this dynamic
78
- st.info(f"Fetching emails from {label}...")
79
- emails = fetch_emails(service, label)
80
- if emails:
81
- df = pd.DataFrame(emails)
82
- st.dataframe(df)
83
- csv = df.to_csv(index=False).encode('utf-8')
84
- st.download_button("Download Emails as CSV", csv, f"{label}_emails.csv", "text/csv")
85
- else:
86
- st.warning(f"No emails found in {label}.")
87
- else:
88
- st.error("You are not authenticated. Please authenticate again.")
89
 
90
  # Fetch Emails from Gmail API
91
  def fetch_emails(service, label):
92
  emails = []
93
- next_page_token = None
94
- total_emails = 0
95
-
96
- # Get total emails
97
- results = service.users().messages().list(userId='me', labelIds=[label], maxResults=1).execute()
98
- total_emails = results.get('resultSizeEstimate', 0)
99
- st.info(f"Total emails in {label}: {total_emails}")
100
-
101
- progress_bar = st.progress(0)
102
-
103
- while True:
104
- results = service.users().messages().list(
105
- userId='me', labelIds=[label], maxResults=100, pageToken=next_page_token
106
- ).execute()
107
- messages = results.get('messages', [])
108
- for message in messages:
109
- msg = service.users().messages().get(userId='me', id=message['id'], format='full').execute()
110
- headers = {header['name']: header['value'] for header in msg['payload']['headers']}
111
- body = ''
112
- if 'parts' in msg['payload']:
113
- for part in msg['payload']['parts']:
114
- if part['mimeType'] == 'text/plain':
115
- body = base64.urlsafe_b64decode(part['body'].get('data', '').encode('UTF-8')).decode('UTF-8')
116
- email_data = {
117
- "Date": headers.get('Date', ''),
118
- "From": headers.get('From', ''),
119
- "To": headers.get('To', ''),
120
- "Subject": headers.get('Subject', ''),
121
- "Snippet": msg.get('snippet', ''),
122
- "Body": body,
123
- "Attachments": "Yes" if 'attachmentId' in str(msg['payload']) else "No",
124
- }
125
- emails.append(email_data)
126
-
127
- progress_bar.progress(min(len(emails) / total_emails, 1.0))
128
- next_page_token = results.get('nextPageToken')
129
- if not next_page_token:
130
- break
131
-
132
- st.success(f"Fetched {len(emails)} emails from {label}")
133
  return emails
134
 
135
  # Main Page
@@ -153,16 +119,19 @@ def main_page():
153
  if not user_email or not app_password or not credentials_file:
154
  st.error("Please provide all required inputs (Gmail, App Password, credentials.json)")
155
  else:
156
- # Save credentials.json locally
157
  with open("credentials.json", "wb") as f:
158
  f.write(credentials_file.getbuffer())
159
- authenticate_gmail("credentials.json")
160
-
161
- # Display Authentication Status
162
- if st.session_state.authenticated:
163
- st.success("You are authenticated!")
164
- else:
165
- st.warning("You are not authenticated yet.")
 
 
 
 
166
 
167
  # Navigation
168
  if "page" not in st.session_state:
 
28
  if creds and creds.valid:
29
  st.session_state.creds = creds
30
  st.session_state.authenticated = True
31
+ st.success("Authentication successful!")
32
+ return creds
33
  except Exception as e:
34
  st.error(f"Invalid token.json file: {e}")
35
  os.remove('token.json')
 
38
  if st.session_state.creds and st.session_state.creds.expired and st.session_state.creds.refresh_token:
39
  st.session_state.creds.refresh(Request())
40
  st.session_state.authenticated = True
41
+ st.success("Authentication successful!")
42
+ return st.session_state.creds
43
  else:
44
  if not st.session_state.flow:
45
  st.session_state.flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
 
56
  st.session_state.flow.fetch_token(code=auth_code)
57
  st.session_state.creds = st.session_state.flow.credentials
58
  st.session_state.authenticated = True
 
59
  with open('token.json', 'w') as token_file:
60
  json.dump({
61
  "token": st.session_state.creds.token,
 
65
  "client_secret": st.session_state.creds.client_secret,
66
  "scopes": st.session_state.creds.scopes
67
  }, token_file)
68
+ st.success("Authentication successful!")
 
69
  except Exception as e:
70
  st.error(f"Error during authentication: {e}")
71
 
72
+ return st.session_state.creds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  # Fetch Emails from Gmail API
75
  def fetch_emails(service, label):
76
  emails = []
77
+ results = service.users().messages().list(userId='me', labelIds=[label], maxResults=100).execute()
78
+ messages = results.get('messages', [])
79
+
80
+ for message in messages:
81
+ msg = service.users().messages().get(userId='me', id=message['id'], format='full').execute()
82
+ headers = {header['name']: header['value'] for header in msg['payload']['headers']}
83
+ body = ''
84
+ if 'parts' in msg['payload']:
85
+ for part in msg['payload']['parts']:
86
+ if part['mimeType'] == 'text/plain':
87
+ body = base64.urlsafe_b64decode(part['body'].get('data', '').encode('UTF-8')).decode('UTF-8')
88
+ email_data = {
89
+ "Date": headers.get('Date', ''),
90
+ "From": headers.get('From', ''),
91
+ "To": headers.get('To', ''),
92
+ "Subject": headers.get('Subject', ''),
93
+ "Snippet": msg.get('snippet', ''),
94
+ "Body": body,
95
+ }
96
+ emails.append(email_data)
97
+
98
+ st.success(f"Fetched {len(emails)} emails from {label}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  return emails
100
 
101
  # Main Page
 
119
  if not user_email or not app_password or not credentials_file:
120
  st.error("Please provide all required inputs (Gmail, App Password, credentials.json)")
121
  else:
 
122
  with open("credentials.json", "wb") as f:
123
  f.write(credentials_file.getbuffer())
124
+ creds = authenticate_gmail("credentials.json")
125
+ if creds:
126
+ service = build('gmail', 'v1', credentials=creds)
127
+ label = st.selectbox("Select Label", ["INBOX", "SENT", "DRAFTS", "TRASH", "SPAM"])
128
+ if st.button("Fetch Emails"):
129
+ emails = fetch_emails(service, label)
130
+ if emails:
131
+ df = pd.DataFrame(emails)
132
+ st.dataframe(df)
133
+ csv = df.to_csv(index=False).encode('utf-8')
134
+ st.download_button("Download Emails as CSV", csv, f"{label}_emails.csv", "text/csv")
135
 
136
  # Navigation
137
  if "page" not in st.session_state: