email-amazon/lambda/lambda_function_bounce.py

97 lines
3.1 KiB
Python

import json
import boto3
import os
from datetime import datetime
# AWS Clients
s3 = boto3.client('s3')
sqs = boto3.client('sqs')
dynamodb = boto3.resource('dynamodb')
# DynamoDB Table
OUTBOUND_TABLE = os.environ.get('OUTBOUND_TABLE', 'ses-outbound-messages')
table = dynamodb.Table(OUTBOUND_TABLE)
def lambda_handler(event, context):
"""
Verarbeitet SES Events:
- Bounce Events: Speichert bounce details in DynamoDB
- Send Events: Ignoriert (nicht mehr benötigt)
"""
print(f"Received event: {json.dumps(event)}")
# SNS Wrapper entpacken
for record in event.get('Records', []):
if 'Sns' in record:
message = json.loads(record['Sns']['Message'])
else:
message = record
event_type = message.get('eventType')
if event_type == 'Bounce':
handle_bounce(message)
elif event_type == 'Send':
# Ignorieren - wird nicht mehr benötigt
print(f"Ignoring Send event (no longer needed)")
else:
print(f"Unknown event type: {event_type}")
return {'statusCode': 200}
def handle_bounce(message):
"""
Verarbeitet Bounce Events und speichert Details in DynamoDB
"""
try:
bounce = message.get('bounce', {})
mail = message.get('mail', {})
# Extrahiere relevante Daten
feedback_id = bounce.get('feedbackId') # Das ist die Message-ID!
bounce_type = bounce.get('bounceType', 'Unknown')
bounce_subtype = bounce.get('bounceSubType', 'Unknown')
bounced_recipients = [r['emailAddress'] for r in bounce.get('bouncedRecipients', [])]
timestamp = bounce.get('timestamp')
# Original Message Daten
original_source = mail.get('source')
original_message_id = mail.get('messageId')
if not feedback_id:
print(f"Warning: No feedbackId in bounce event")
return
print(f"Processing bounce: feedbackId={feedback_id}, type={bounce_type}/{bounce_subtype}")
print(f"Bounced recipients: {bounced_recipients}")
# Speichere in DynamoDB (feedback_id ist die Message-ID der Bounce-Mail!)
table.put_item(
Item={
'MessageId': feedback_id, # Primary Key
'original_message_id': original_message_id, # SES MessageId der Original-Mail
'original_source': original_source,
'bounceType': bounce_type,
'bounceSubType': bounce_subtype,
'bouncedRecipients': bounced_recipients, # Liste von Email-Adressen
'timestamp': timestamp or datetime.utcnow().isoformat(),
'event_type': 'bounce'
}
)
print(f"✓ Stored bounce info for feedbackId {feedback_id}")
except Exception as e:
print(f"Error handling bounce: {e}")
import traceback
traceback.print_exc()
def handle_send(message):
"""
DEPRECATED - Wird nicht mehr benötigt
Send Events werden jetzt ignoriert
"""
pass