How to send a mail with multiple attachments and custom file names using Mailgun (from Python)

StackOverflow https://stackoverflow.com/questions/21566158

  •  07-10-2022
  •  | 
  •  

Question

(As Mailgun doesn't have a python library this applies for both CURL and Python)

We are working on a sandboxed server without access to the filesystem.

This is the example provided by mailgun:

def send_complex_message():
    return requests.post(
        "https://api.mailgun.net/v2/samples.mailgun.org/messages",
        auth=("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"),
        files=[("attachment", open("files/test.jpg")),
               ("attachment", open("files/test.txt"))],
        data={"from": "Excited User <me@samples.mailgun.org>",
              "to": "foo@example.com",
              "cc": "baz@example.com",
              "bcc": "bar@example.com",
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!",
              "html": "<html>HTML version of the body</html>"})

As you can see the filename is only implied on the open() calls.

Given that we have no access to the filesystem, we download the files from a remote location and pass the data.

This sends the data in the mail but the filenames are ignored, this makes it almost impossible for clients to open the files as they would have to guess the file extension for every attachment.

How do we specify the filenames manually?

Thanks!

Was it helpful?

Solution

After digging around for a while I discovered a sample showing exactly how to do this here.

I am leaving that code here for future reference as it was very useful:

def send_complex_message():
    return requests.post("https://api.mailgun.net/v2/DOMAIN/messages",
              auth=("api", "key-SECRET"),
              files={
                  "attachment[0]": ("FileName1.ext", open(FILE_PATH_1, 'rb')),
                  "attachment[1]": ("FileName2.ext", open(FILE_PATH_2, 'rb'))
              },
              data={"from": "FROM_EMAIL",
                    "to": [TO_EMAIL],
                    "subject": SUBJECT,
                    "html": HTML_CONTENT
              })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top