Created
February 21, 2025 02:41
-
-
Save levancho/d17e8125b1411b074a04c72c07ba525d to your computer and use it in GitHub Desktop.
processA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import psycopg2 | |
from datetime import datetime | |
from exchangelib import Credentials, Account, DELEGATE | |
# Outlook Configuration | |
OUTLOOK_EMAIL = "[email protected]" # Your technical user email | |
OUTLOOK_PASSWORD = "your_password" # Your password | |
SHARED_MAILBOX = "[email protected]" # The shared mailbox | |
FOLDER_NAME = "Inbox" # Folder to check emails from | |
ATTACHMENT_DIR = "./attachments" # Directory to save attachments | |
# PostgreSQL Database Configuration | |
DB_CONFIG = { | |
"dbname": "your_database", | |
"user": "your_db_user", | |
"password": "your_db_password", | |
"host": "your_db_host", | |
"port": "5432" | |
} | |
# Ensure attachment directory exists | |
os.makedirs(ATTACHMENT_DIR, exist_ok=True) | |
# Connect to Outlook using exchangelib | |
credentials = Credentials(OUTLOOK_EMAIL, OUTLOOK_PASSWORD) | |
account = Account( | |
primary_smtp_address=SHARED_MAILBOX, | |
credentials=credentials, | |
autodiscover=True, | |
access_type=DELEGATE | |
) | |
# Connect to PostgreSQL | |
conn = psycopg2.connect(**DB_CONFIG) | |
cursor = conn.cursor() | |
# Create table if it doesn't exist | |
cursor.execute(""" | |
CREATE TABLE IF NOT EXISTS email_records ( | |
oid SERIAL PRIMARY KEY, | |
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
senders TEXT, | |
documents TEXT, | |
status TEXT | |
) | |
""") | |
conn.commit() | |
# Access the shared folder | |
folder = account.inbox # Default to Inbox, modify if needed | |
# Process unread emails | |
for email in folder.filter(is_read=False): | |
sender_email = email.sender.email_address if email.sender else "Unknown" | |
document_names = [] | |
# Process attachments | |
for attachment in email.attachments: | |
if hasattr(attachment, 'content'): | |
file_path = os.path.join(ATTACHMENT_DIR, attachment.name) | |
with open(file_path, 'wb') as f: | |
f.write(attachment.content) | |
document_names.append(attachment.name) | |
# Insert record into the PostgreSQL database | |
cursor.execute(""" | |
INSERT INTO email_records (created_on, senders, documents, status) | |
VALUES (%s, %s, %s, %s) | |
""", (datetime.now(), sender_email, ", ".join(document_names), "Downloaded")) | |
# Mark email as read | |
email.is_read = True | |
email.save() | |
# Delete email after processing | |
email.delete() | |
# Commit and close database connection | |
conn.commit() | |
cursor.close() | |
conn.close() | |
print("Processing completed successfully. Emails processed and deleted.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment