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

馋奶兔 提交于 2019-12-07 16:44:33

问题


(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!


回答1:


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
              })


来源:https://stackoverflow.com/questions/21566158/how-to-send-a-mail-with-multiple-attachments-and-custom-file-names-using-mailgun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!