102 lines
3.5 KiB
Python
102 lines
3.5 KiB
Python
import os
|
|
import requests
|
|
import msal
|
|
|
|
# ==============================================================================
|
|
# KONFIGURATION
|
|
# ==============================================================================
|
|
# Daten aus der Azure App Registration
|
|
TENANT_ID = "caee3499-03f8-4175-9fa8-a935248d0ece"
|
|
CLIENT_ID = "3a08b279-1fc3-419f-a77e-31f12a0f65f7"
|
|
CLIENT_SECRET = "Rk-8Q~nJ.sZ-xUiNxtEDdzVgoFFosODLVHX~jdrh"
|
|
|
|
# Überwachtes Postfach
|
|
USER_EMAIL = "i.meszely@aps-hh.de"
|
|
|
|
# Microsoft Graph API Endpunkte
|
|
GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0"
|
|
AUTHORITY_URL = f"https://login.microsoftonline.com/{TENANT_ID}"
|
|
SCOPES = ["https://graph.microsoft.com/.default"]
|
|
|
|
def get_graph_api_token():
|
|
"""Ruft das Zugriffstoken für die Microsoft Graph API ab."""
|
|
app = msal.ConfidentialClientApplication(
|
|
client_id=CLIENT_ID,
|
|
authority=AUTHORITY_URL,
|
|
client_credential=CLIENT_SECRET
|
|
)
|
|
result = app.acquire_token_silent(scopes=SCOPES, account=None)
|
|
if not result:
|
|
result = app.acquire_token_for_client(scopes=SCOPES)
|
|
|
|
if "access_token" in result:
|
|
return result["access_token"]
|
|
else:
|
|
print("Fehler beim Abrufen des Tokens!")
|
|
print(result.get("error"))
|
|
print(result.get("error_description"))
|
|
return None
|
|
|
|
def list_inbox_emails(access_token):
|
|
"""Listet ungelesene E-Mails aus dem INBOX."""
|
|
headers = {"Authorization": f"Bearer {access_token}"}
|
|
|
|
# Nur notwendige Felder aus Effizienzgründen abrufen
|
|
messages_url = (
|
|
f"{GRAPH_API_ENDPOINT}/users/{USER_EMAIL}/mailFolders/inbox/messages?"
|
|
f"$filter=isRead eq false&"
|
|
f"$select=from,subject,receivedDateTime&"
|
|
f"$orderby=receivedDateTime desc"
|
|
)
|
|
|
|
response = requests.get(messages_url, headers=headers)
|
|
response.raise_for_status()
|
|
messages = response.json().get("value", [])
|
|
|
|
if not messages:
|
|
print("Keine neuen ungelesenen E-Mails im INBOX-Ordner.")
|
|
return
|
|
|
|
print(f"\n{len(messages)} ungelesene E-Mails gefunden:")
|
|
print("=" * 60)
|
|
|
|
for i, message in enumerate(messages, 1):
|
|
from_email = message.get("from", {}).get("emailAddress", {})
|
|
sender = from_email.get("address", "Unbekannt")
|
|
subject = message.get("subject", "Kein Betreff")
|
|
received = message.get("receivedDateTime", "")
|
|
|
|
# Datum formatieren
|
|
if received:
|
|
try:
|
|
from datetime import datetime
|
|
dt = datetime.fromisoformat(received.replace('Z', '+00:00'))
|
|
formatted_date = dt.strftime("%Y-%m-%d %H:%M")
|
|
except:
|
|
formatted_date = received[:19] # Einfache Formatierung bei Fehler
|
|
else:
|
|
formatted_date = "Unbekannt"
|
|
|
|
print(f"\n{i}. {sender}")
|
|
print(f" Betreff: {subject}")
|
|
print(f" Zeit: {formatted_date}")
|
|
|
|
def main():
|
|
"""Hauptfunktion."""
|
|
print("Graph API Token wird abgerufen...")
|
|
access_token = get_graph_api_token()
|
|
if not access_token:
|
|
return
|
|
|
|
try:
|
|
list_inbox_emails(access_token)
|
|
except requests.HTTPError as e:
|
|
print(f"Fehler beim Abrufen der E-Mails: {e}")
|
|
if "403" in str(e):
|
|
print("403 Fehler: Wahrscheinlich fehlende Mail.Read Berechtigung.")
|
|
print("Überprüfen Sie die API-Berechtigungen in der Azure App Registration!")
|
|
except Exception as e:
|
|
print(f"Unerwarteter Fehler: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
main() |