import boto3 import os import json from urllib.request import urlopen from urllib.error import URLError, HTTPError def lambda_handler(event, context): api_url = "https://shortstories-api.onrender.com/" ses = boto3.client('ses', region_name='us-east-1') sender = "story-time@sharathonline.com" recipient = os.environ.get('RECIPIENT_EMAIL') # IF no moral then send the below as a subject subject = "Story Time!" try: with urlopen(api_url, timeout=10) as response: data = json.loads(response.read().decode("utf-8")) body = data.get("story") subject = "Moral of the story: " + data.get("moral") print(data.get("story")) if not recipient: return { 'statusCode': 400, 'body': 'Recipient email not set in environment variables.' } recipients = [email.strip() for email in recipient.replace(';', ',').split(',') if email.strip()] print("recipients: ", recipients) response = ses.send_email( Source=sender, Destination={'ToAddresses': recipients}, Message={ 'Subject': {'Data': subject}, 'Body': {'Text': {'Data': body}} } ) return { 'statusCode': 200, 'body': 'Email sent!', 'ses_response': response } except HTTPError as e: print(f"ERROR: HTTP Error: {e.code} - {e.reason}") return {'statusCode': e.code, 'body': json.dumps({"error": f"API HTTP error: {e.reason}"})} except URLError as e: print(f"ERROR: Request Error: {e.reason}") return {'statusCode': 500, 'body': json.dumps({"error": f"API call failed: {e.reason}"})}