docker/email_api/app.py

55 lines
1.9 KiB
Python

import sys
from flask import Flask, request, jsonify
import smtplib
import base64
import gzip
import logging
import os
# Python-Version prüfen
if sys.version_info < (3, 12):
raise RuntimeError("Python 3.12 oder höher erforderlich")
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Konfiguration
SMTP_HOST = "postfix" # MailCow Postfix-Container
SMTP_PORT = 25 # Fest auf Port 25 ohne TLS
API_TOKEN = os.environ.get('API_TOKEN', 'your-api-token') # Muss mit Lambda übereinstimmen
@app.route('/process/<domain>', methods=['POST'])
def process_email(domain):
# Authentifizierung via Bearer-Token
auth_header = request.headers.get('Authorization')
if not auth_header or auth_header != f'Bearer {API_TOKEN}':
return jsonify({'error': 'Unauthorized'}), 401
data = request.get_json()
request_id = data.get('request_id')
email_content = data.get('email_content')
compressed = data.get('compressed', False)
logger.info(f"[{request_id}] Processing email for domain: {domain}")
try:
# Entkomprimieren, falls komprimiert
if compressed:
email_bytes = base64.b64decode(email_content)
email_content = gzip.decompress(email_bytes).decode('utf-8')
else:
email_content = base64.b64decode(email_content).decode('utf-8')
# An Postfix lokal weiterleiten (Port 25, kein TLS)
with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp:
smtp.sendmail('lambda@andreasknuth.de', f'inbox@{domain}', email_content)
logger.info(f"[{request_id}] Email forwarded to Postfix for {domain}")
return jsonify({'message': 'Email processed', 'request_id': request_id}), 200
except Exception as e:
logger.error(f"[{request_id}] Error processing email: {str(e)}")
return jsonify({'error': str(e), 'request_id': request_id}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)