wahab5763 commited on
Commit
144b99c
·
verified ·
1 Parent(s): 160f1c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -63
app.py CHANGED
@@ -17,10 +17,12 @@ if "creds" not in st.session_state:
17
  st.session_state.creds = None
18
  if "auth_url" not in st.session_state:
19
  st.session_state.auth_url = None
 
 
20
  if "flow" not in st.session_state:
21
  st.session_state.flow = None
22
 
23
- # Authenticate Gmail API
24
  def authenticate_gmail(credentials_file):
25
  if os.path.exists('token.json'):
26
  try:
@@ -50,28 +52,26 @@ def authenticate_gmail(credentials_file):
50
  st.info("Please visit this URL to authorize the application:")
51
  st.code(st.session_state.auth_url)
52
 
53
- auth_code = st.text_input("Enter the authorization code:")
54
- if st.button("Submit Authentication Code"):
55
- try:
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,
62
- "refresh_token": st.session_state.creds.refresh_token,
63
- "token_uri": st.session_state.creds.token_uri,
64
- "client_id": st.session_state.creds.client_id,
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()
@@ -98,44 +98,31 @@ def fetch_emails(service, label):
98
  st.success(f"Fetched {len(emails)} emails from {label}.")
99
  return emails
100
 
 
101
  # Main Page
102
- def main_page():
103
- st.sidebar.title("Steps to Use")
104
- st.sidebar.write("""
105
- 1. Enable Gmail API from [Google Cloud Console](https://console.cloud.google.com/).
106
- 2. Download the `credentials.json` file.
107
- 3. Enter your Gmail email and App Password.
108
- 4. Upload your `credentials.json` file.
109
- 5. Authenticate and proceed to fetch emails.
110
- """)
111
-
112
- st.title("Gmail Email Fetcher")
113
-
114
- user_email = st.text_input("Gmail Email")
115
- app_password = st.text_input("App Password", type="password")
116
- credentials_file = st.file_uploader("Upload credentials.json", type="json")
117
-
118
- if st.button("Authenticate"):
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:
138
- st.session_state.page = "main"
139
-
140
- if st.session_state.page == "main":
141
- main_page()
 
17
  st.session_state.creds = None
18
  if "auth_url" not in st.session_state:
19
  st.session_state.auth_url = None
20
+ if "auth_code" not in st.session_state:
21
+ st.session_state.auth_code = ""
22
  if "flow" not in st.session_state:
23
  st.session_state.flow = None
24
 
25
+
26
  def authenticate_gmail(credentials_file):
27
  if os.path.exists('token.json'):
28
  try:
 
52
  st.info("Please visit this URL to authorize the application:")
53
  st.code(st.session_state.auth_url)
54
 
55
+
56
+ def submit_auth_code():
57
+ try:
58
+ st.session_state.flow.fetch_token(code=st.session_state.auth_code)
59
+ st.session_state.creds = st.session_state.flow.credentials
60
+ st.session_state.authenticated = True
61
+ with open('token.json', 'w') as token_file:
62
+ json.dump({
63
+ "token": st.session_state.creds.token,
64
+ "refresh_token": st.session_state.creds.refresh_token,
65
+ "token_uri": st.session_state.creds.token_uri,
66
+ "client_id": st.session_state.creds.client_id,
67
+ "client_secret": st.session_state.creds.client_secret,
68
+ "scopes": st.session_state.creds.scopes
69
+ }, token_file)
70
+ st.success("Authentication successful!")
71
+ except Exception as e:
72
+ st.error(f"Error during authentication: {e}")
73
+
74
+
 
 
75
  def fetch_emails(service, label):
76
  emails = []
77
  results = service.users().messages().list(userId='me', labelIds=[label], maxResults=100).execute()
 
98
  st.success(f"Fetched {len(emails)} emails from {label}.")
99
  return emails
100
 
101
+
102
  # Main Page
103
+ st.title("Gmail Email Fetcher")
104
+
105
+ credentials_file = st.file_uploader("Upload credentials.json", type="json")
106
+ if credentials_file:
107
+ with open("credentials.json", "wb") as f:
108
+ f.write(credentials_file.getbuffer())
109
+ authenticate_gmail("credentials.json")
110
+
111
+ if st.session_state.auth_url:
112
+ st.text_input("Enter the authorization code:", key="auth_code")
113
+ if st.button("Submit Authentication Code"):
114
+ submit_auth_code()
115
+
116
+ if st.session_state.authenticated:
117
+ st.success("You are authenticated!")
118
+ service = build('gmail', 'v1', credentials=st.session_state.creds)
119
+ label = st.selectbox("Select Label", ["INBOX", "SENT", "DRAFTS", "TRASH", "SPAM"])
120
+ if st.button("Fetch Emails"):
121
+ emails = fetch_emails(service, label)
122
+ if emails:
123
+ df = pd.DataFrame(emails)
124
+ st.dataframe(df)
125
+ csv = df.to_csv(index=False).encode('utf-8')
126
+ st.download_button("Download Emails as CSV", csv, f"{label}_emails.csv", "text/csv")
127
+ else:
128
+ st.warning("You are not authenticated yet.")