[Python] Empty PDF attachment using fpdf2 with boto3 sesv2

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm facing an issue with empty PDF attachments sent with boto3 SESv2 client using Templated Email type.

    I think this is something related to encoding or specific boto3 send_email rules that I'm not following, but IDK which exactly. Saving file locally works totally correct.

    docs I'm using: https://boto3.amazonaws.com/v1/docu...ference/services/sesv2/client/send_email.html

    https://py-pdf.github.io/fpdf2/index.html

    class AttachmentDict(TypedDict):
    RawContent: bytes
    ContentDisposition: Literal["ATTACHMENT", "INLINE"]
    FileName: str
    ContentId: str
    ContentType: Literal["application/pdf", "image/jpeg"]


    def send_templated_email(email_request: EmailTemplateRequest) -> str:
    """
    Sends an email based on a template. A template contains replaceable tags
    each enclosed in two curly braces, such as {{name}}. The template data passed
    in this function contains key-value pairs that define the values to insert
    in place of the template tags.

    :param email_request: data that contains necessary details for email
    :return: The ID of the message, assigned by Amazon SES.
    """
    send_args: TemplatedEmailArgs = {
    "FromEmailAddress": email_request.source,
    "Destination": {"ToAddresses": email_request.recipients},
    "Content": {
    "Template": {
    "TemplateName": email_request.template_name,
    "TemplateData": email_request.template_data.model_dump_json(),
    "Attachments": [],
    },
    },
    }

    # Add attachments if any
    for attachment in email_request.attachments:
    attachment_arg: AttachmentDict = {
    "RawContent": attachment.content,
    "ContentDisposition": "ATTACHMENT",
    "FileName": attachment.filename,
    "ContentType": "application/pdf",
    }
    send_args["Content"]["Template"]["Attachments"].append(attachment_arg)

    response = email_client.send_email(**send_args)



    The content for attachment is assembled for fpdf2 library like this

    So on the line "RawContent": attachment.content attachment.content is file_content (bytes type)

    pdf_file = fpdf.FPDF(orientation="P", unit="mm", format="A4")
    pdf_file.add_page()
    pdf_file.set_auto_page_break(auto=True, margin=15)
    # ... Generation of content
    file_content = pdf_file.output() # This file content goes to "RawContent" as bytes



    But in the end I see PDF attachment with an empty body, but correct page number. [​IMG]

    Continue reading...

Compartilhe esta Página