add an attachment along with templated email

0

I need to attach a pdf to the templated email , how can i do that ?

asked a year ago1145 views
1 Answer
0

Hello,

To attach a PDF file to an Amazon SES templated email, you'll need to use the SendTemplatedEmail action along with a MIME message to include the PDF attachment. F.ex:

import base64
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

# Set your AWS region, sender email, recipient email, template name, and PDF file path
REGION = 'us-west-2'
SENDER = 'sender@example.com'
RECIPIENT = 'recipient@example.com'
TEMPLATE_NAME = 'YourTemplateName'
PDF_FILE = 'path/to/yourfile.pdf'

# Initialize the SES client
ses_client = boto3.client('ses', region_name=REGION)

# Create the MIME container for the email
msg = MIMEMultipart()

# Add the email template
msg.attach(MIMEText(f'{{"Template": "{TEMPLATE_NAME}"}}', 'ses'))

# Attach the PDF file
with open(PDF_FILE, 'rb') as f:
    pdf_data = f.read()
attachment = MIMEApplication(pdf_data, 'pdf')
attachment.add_header('Content-Disposition', 'attachment', filename='yourfile.pdf')
msg.attach(attachment)

# Encode the MIME message
raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8')

# Send the email
response = ses_client.send_raw_email(
    Source=SENDER,
    Destinations=[RECIPIENT],
    RawMessage={
        'Data': raw_message
    }
)

print(f"Email sent! Message ID: {response['MessageId']}")

Hope it helps,

Regards,

Jorge
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions