import streamlit as st import pandas as pd import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import gspread from oauth2client.service_account import ServiceAccountCredentials from streamlit_option_menu import option_menu from io import BytesIO import requests from email.mime.application import MIMEApplication import os # Function to read files from local path def read_file(path): try: with open(path, 'rb') as file: return file.read() except Exception as e: st.error(f"Failed to read file from {path}: {str(e)}") return None # Function to get file content type based on file extension def get_content_type(file_path): if file_path.lower().endswith('.pdf'): return 'application/pdf' elif file_path.lower().endswith('.csv'): return 'text/csv' elif file_path.lower().endswith('.xlsx'): return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' else: return 'application/octet-stream' # Define your email server details EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'ninadmandavkar@gofynd.com' EMAIL_HOST_PASSWORD = 'vxay jiss cctw lsdo' st.set_page_config(page_title="Alerter",page_icon="",layout="centered") html_title = """

Alerter

""" st.markdown(html_title, unsafe_allow_html=True) menu_options = [ {"label": "Internal users", "icon": "📄", "description": "Upload a document and schedule it for email"}, {"label": "External users", "icon": "📊", "description": "Schedule an email with BigQuery data"}, {"label": "Recon checking", "icon": "📊", "description": "Schedule an email with BigQuery data"}, {"label": "Manual BQ upload", "icon": "📊", "description": "Schedule an email with BigQuery data"}, {"label": "Invoice splitter", "icon": "📊", "description": "Schedule an email with BigQuery data"}, {"label": "Seller sale validation", "icon": "📊", "description": "Schedule an email with BigQuery data"}, # {"label": "MID checker", "icon": "📊", "description": "Schedule an email with BigQuery data"}, {"label": "Payment working", "icon": "📊", "description": "Schedule an email with BigQuery data"} ] # Create the custom option menu selected_option = option_menu( menu_title="Select Integration", # Title of the menu options=[option["label"] for option in menu_options], # Displayed options icons=[option["icon"] for option in menu_options], # Icons next to options menu_icon="cast", # Icon for the entire menu default_index=0, # Default selected option orientation="horizontal" # Orientation of the menu (can be vertical or horizontal) ) if selected_option == "External users": html_subject = """

Select an option

""" st.markdown(html_subject, unsafe_allow_html=True) upload_option = st.radio("", ["Upload Spreadsheet (CSV or Excel)", "Google Sheets URL"]) if upload_option == "Upload Spreadsheet (CSV or Excel)": html_subject = """

Upload documents

""" st.markdown(html_subject, unsafe_allow_html=True) uploaded_file = st.file_uploader("", type=["csv", "xlsx"]) if uploaded_file: # Load the data if uploaded_file.name.endswith(".csv"): df = pd.read_csv(uploaded_file) else: df = pd.read_excel(uploaded_file) st.write("") st.write("") elif upload_option == "Google Sheets URL": html_subject = """

Enter Google sheets url

""" st.markdown(html_subject, unsafe_allow_html=True) sheet_url = st.text_input("") if sheet_url: try: # Define the scope scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/drive'] # Add credentials creds = ServiceAccountCredentials.from_json_keyfile_name('fynd-db-48954327ef17.json', scope) client = gspread.authorize(creds) # Get the sheet data sheet = client.open_by_url(sheet_url).sheet1 data = sheet.get_all_records() df = pd.DataFrame(data) except Exception as e: st.error(f"Failed to load Google Sheets: {str(e)}") if 'df' in locals(): # Display the data (excluding the 'status' column) df = df.drop(columns=['status'], errors='ignore') st.dataframe(df) button_styles = """ """ st.markdown(button_styles, unsafe_allow_html=True) if st.button("Send Emails"): # Send emails for index, row in df.iterrows(): email = row['Email Addresses'] subject = row['Subject'] message = row['Message'] cc_addresses = row['CC Addresses'].split(',') if 'CC Addresses' in row else [] Folder_IDs = row['Folder IDs'].split(',') # company_name = row['Company_Name'] # company_id = row['Company_ID'] # Create the email msg = MIMEMultipart() msg['From'] = EMAIL_HOST_USER msg['To'] = email msg['Subject'] = subject if cc_addresses: msg['Cc'] = ','.join(cc_addresses) body = f"""{message}""" msg.attach(MIMEText(body, 'plain')) # Read and attach PDFs for folder_id in Folder_IDs: pdf_path = folder_id.strip() if pdf_path.endswith('.pdf'): pdf_content = read_file(pdf_path) if pdf_content: part = MIMEApplication(pdf_content, Name=os.path.basename(pdf_path)) part['Content-Disposition'] = f'attachment; filename="{os.path.basename(pdf_path)}"' msg.attach(part) # Read and attach CSV files for folder_id in Folder_IDs: csv_path = folder_id.strip() if csv_path.endswith('.csv'): csv_content = read_file(csv_path) if csv_content: part = MIMEApplication(csv_content, Name=os.path.basename(csv_path)) part['Content-Disposition'] = f'attachment; filename="{os.path.basename(csv_path)}"' msg.attach(part) # Read and attach XLSX files for folder_id in Folder_IDs: xlsx_path = folder_id.strip() if xlsx_path.endswith('.xlsx'): xlsx_content = read_file(xlsx_path) if xlsx_content: part = MIMEApplication(xlsx_content, Name=os.path.basename(xlsx_path)) part['Content-Disposition'] = f'attachment; filename="{os.path.basename(xlsx_path)}"' msg.attach(part) # Read and attach ZIP files for folder_id in Folder_IDs: zip_path = folder_id.strip() if zip_path.endswith('.zip'): zip_content = read_file(zip_path) if zip_content: part = MIMEApplication(zip_content, Name=os.path.basename(zip_path)) part['Content-Disposition'] = f'attachment; filename="{os.path.basename(zip_path)}"' msg.attach(part) # Send the email try: with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server: server.starttls() server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) server.sendmail(msg['From'], [email] + cc_addresses, msg.as_string()) st.success(f"Email sent to {email}") except Exception as e: st.error(f"Failed to send email to {email}: {str(e)}") elif selected_option == "Internal users": with open('ap.py') as file: exec(file.read()) elif selected_option == "Recon checking": with open('recon.py') as file: exec(file.read()) elif selected_option == "Manual BQ upload": with open('bq.py') as file: exec(file.read()) elif selected_option == "Invoice splitter": with open('splitter.py') as file: exec(file.read()) elif selected_option == "Seller sale validation": with open('seller.py') as file: exec(file.read()) elif selected_option == "Payment working": with open('payments.py') as file: exec(file.read())