Skip to content

Instantly share code, notes, and snippets.

@robes7
Created February 15, 2025 12:05
Show Gist options
  • Select an option

  • Save robes7/460d6aee36aab892db027d254df15406 to your computer and use it in GitHub Desktop.

Select an option

Save robes7/460d6aee36aab892db027d254df15406 to your computer and use it in GitHub Desktop.
Select from DB, export file and send it via mail
import cx_Oracle
import pandas as pd
import smtplib
import os
from email.message import EmailMessage
# Database Connection Details
DB_CONNECTION_STRING = "add connection string here"
# Email Configuration
SMTP_SERVER = "smtp server"
SMTP_PORT = 25
EMAIL_USER = "sender"
EMAIL_ALIAS = "alias"
EMAIL_TO = ["recipient1", "recipient2"]
# Query
QUERY = """
SELECT
"""
# Output File
OUTPUT_FILE = "output_file.xlsx"
def fetch_data():
"""Connects to Oracle DB and fetches query results into a DataFrame."""
try:
with cx_Oracle.connect(DB_CONNECTION_STRING) as conn:
df = pd.read_sql(QUERY, conn)
return df
except Exception as e:
print(f"Database error: {e}")
return None
def save_to_excel(df):
"""Saves DataFrame to an Excel file."""
df.to_excel(OUTPUT_FILE, index=False)
print(f"Data saved to {OUTPUT_FILE}")
def send_email():
"""Sends the Excel file via email."""
msg = EmailMessage()
msg['Subject'] = "Subject of mail"
msg['From'] = EMAIL_ALIAS
msg['To'] = ", ".join(EMAIL_TO)
msg.set_content("Content of mail.")
with open(OUTPUT_FILE, "rb") as f:
msg.add_attachment(f.read(), maintype='application', subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename=OUTPUT_FILE)
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.send_message(msg)
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
def main():
df = fetch_data()
if df is not None:
save_to_excel(df)
send_email()
os.remove(OUTPUT_FILE) # Cleanup after sending
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment