Skip to content

[SOLVED] How to send files and data in the same request #3571

@sevaho

Description

@sevaho

Long story short

I want to send files (binary data) and json data in the same request but failing to grasp the documentation or see any examples in github issues.

Expected behaviour

Send file(s) and post data

Actual behaviour

It doesn't seem to include post parameters

Steps to reproduce

attachment = open("/tmp/some.pdf", "rb")

mailgun_data = {
    "from": "test@test.com",
    "to": "sebastiaan@sevaho.io",
    "subject": "testje",
    "html": "testje",
}

async def main():
    auth = aiohttp.BasicAuth(login="api", password=API_MAILGUN)
    try:
        async with aiohttp.ClientSession(auth=auth) as session:
            with aiohttp.MultipartWriter("mixed") as mpwriter:

                mpwriter.append(attachment, {"Content-Type": "multipart/form-data"})
                mpwriter.append_json(mailgun_data)

                async with session.post(
                    f"https://api.mailgun.net/v3/{ API_MAILGUN_DOMAIN }/messages",
                    data=mpwriter,
                ) as resp:
                    response = await resp.text()
                    print(response)

    except Exception as e:
        print(e)
        raise Exception("something went wrong while sending email")


asyncio.run(main())

output:

{
  "message": "'from' parameter is missing"
}

without the file the request works.

Your environment

I use aiohttp client, on arch linux 4.20.3 aiohttp version: 3.4.4

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions