0

I am using a Python Boto3 script to send bulk emails through Amazon SES. The script is running successfully, but the emails are not being received by the recipients. I have checked the spam folder and tested with different email addresses, but still not receiving the email.

The code logs the Message ID for the emails sent, so I need help in finding the logs for the successful status emails. I have also created a log file to store the email sending status for each recipient.

Here's the code I am using to send the emails:

import boto3
from botocore.exceptions import ClientError
import csv
import json

AWS_REGION = 'MY_AWS_REGION'
AWS_ACCESS_KEY_ID = 'MY_AWS_ACCESS_KEY_ID'
AWS_SECRET_ACCESS_KEY = 'MY_AWS_SECRET_ACCESS_KEY'

SENDER = 'sender@email.com'
SUBJECT_EN = 'Subject in English'
SUBJECT_ES = '"Asunto en espaƱol"'
BODY_EN_HTML = open("en_file.html", "r").read()
BODY_ES_HTML = open("es_file.html", "r", encoding="utf-8").read()
emails_sent = []
email_count = 0
year = 'email_spreadsheet.csv'

client = boto3.client('sesv2', region_name=AWS_REGION, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

try:
    with open(year, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        bulk_email_list = []
        for row in reader:
            email_count += 1
            RECIPIENT = row['Username']
            LANGUAGE = row['Language']

            if LANGUAGE == 'English':
                BODY_HTML = BODY_EN_HTML
                SUBJECT = SUBJECT_EN
            else:
                BODY_HTML = BODY_ES_HTML
                SUBJECT = SUBJECT_ES

            bulk_email_list.append({
                'Destination': {
                    'ToAddresses': [RECIPIENT]
                },
                'ReplacementEmailContent': {
                    'ReplacementTemplate': {
                        'ReplacementTemplateData': json.dumps({
                            'subject': SUBJECT,
                            'html': BODY_HTML
                        })
                    }
                }
            })

            if len(bulk_email_list) == 30:  # Send 30 emails at a time
                response = client.send_bulk_email(
                    BulkEmailEntries=bulk_email_list,
                    FromEmailAddress=SENDER,
                    DefaultContent={
                        'Template': {
                            'TemplateName': 'EmailTemplateBulk',
                            'TemplateData': json.dumps({ 'subject': SUBJECT, 'html': BODY_HTML})
                        }
                    }
                )
                for i, result in enumerate(response['BulkEmailEntryResults']):
                    if 'Error' in result:
                        emails_sent.append({"email": bulk_email_list[i]['Destination']['ToAddresses'][0], "status": str(result['Error'])})
                    else:
                        emails_sent.append({"email": bulk_email_list[i]['Destination']['ToAddresses'][0], "status": f"Email sent to {result['MessageId']}! Message ID:"})
                bulk_email_list = []

        if len(bulk_email_list) > 0:  # Send any remaining emails
            response = client.send_bulk_email(
                BulkEmailEntries=bulk_email_list,
                FromEmailAddress=SENDER,
                DefaultContent={
                    'Template': {
                        'TemplateName': 'EmailTemplateBulk',
                        'TemplateData': json.dumps({ 'subject': SUBJECT, 'html': BODY_HTML})
                    }
                }
            )
            for i, result in enumerate(response['BulkEmailEntryResults']):
                if 'Error' in result:
                    emails_sent.append({"email": bulk_email_list[i]['Destination']['ToAddresses'][0], "status": str(result['Error'])})
                else:
                    print(response)
                    emails_sent.append({"email": bulk_email_list[i]['Destination']['ToAddresses'][0], "status": f"Email sent to {result['MessageId']}! Message ID:"})

except Exception as e:
    for email in emails_sent:
        print(email_count, email)
    print(str(e))

# Print status of emails sent
for email in emails_sent:
    print(email['email'], email['status'])

log_file = open("emails_sent_log" + year, "w")
for email_count, email in enumerate(emails_sent):
    print(email_count, email)
    email_str = json.dumps(email)
    log_file.write(email_str + '\n')
log_file.close()

An example of the print(response) portion of the script below

{'ResponseMetadata': {'RequestId': '<RequestID here>', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Thu, 06 Apr 2023 23:39:23 GMT', 'content-type': 'application/json', 'content-length': '<length of content here>', 'connection': 'keep-alive', 'x-amzn-requestid': '<x-amzn-requestid here>'}, 'RetryAttempts': 0}, 'BulkEmailEntryResults': 
[{'Status': 'SUCCESS', 'MessageId': '<numerical message id here>'}]}

An example of print(email['email'], email['status']) portion below

emailsent@example.com Email sent to <numerical message id here>! Message ID:
0 {'email': 'emailsent@example.com', 'status': 'Email sent to <numerical message id here>! Message ID:'}

Can someone please help me identify what could be causing the issue and how to retrieve logs for the returning a successful status?

I have tried to investigate the issue by checking the AWS SES console for logs and information related to the emails that are not being received. However, I couldn't find any information on the specific emails that were sent successfully but not received. I was expecting to find some information or logs in the console that could help me identify why the emails are not being delivered to the intended recipients. I am logging the Message ID and figured I could use that somewhere.

David Rex
  • 1
  • 1

0 Answers0