使用 python 使用 Mailgun 发送附件

Send attached file with Mailgun using python

我正在尝试使用 requests.post.

使用 Mailgun API 发送带有附件的电子邮件

在他们的文档中,他们警告说 发送附件时必须使用 multipart/form-data 编码,我正在尝试这样做:

import requests
MAILGUN_URL = 'https://api.mailgun.net/v3/sandbox4f...'
MAILGUN_KEY = 'key-f16f497...'


def mailgun(file_url):
    """Send an email using MailGun"""

    f = open(file_url, 'rb')

    r = requests.post(
        MAILGUN_URL,
        auth=("api", MAILGUN_KEY),
        data={
            "subject": "My subject",
            "from": "my_email@gmail.com",
            "to": "to_you@gmail.com",
            "text": "The text",
            "html": "The<br>html",
            "attachment": f
        },
        headers={'Content-type': 'multipart/form-data;'},
    )

    f.close()

    return r


mailgun("/tmp/my-file.xlsx")

我定义了 header 以确保内容类型是 multipart/form-data,但是当我 运行 代码时,我得到一个 400 状态,原因是:Bad Request

怎么了? 我需要确保我正在使用 multipart/form-data 并且我正在正确使用 附件 参数

您需要使用 files 关键字参数。 Here 是请求中的文档。

Mailgun 文档中的示例:

def send_complex_message():
    return requests.post(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        auth=("api", "YOUR_API_KEY"),
        files=[("attachment", open("files/test.jpg")),
               ("attachment", open("files/test.txt"))],
        data={"from": "Excited User <YOU@YOUR_DOMAIN_NAME>",
              "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>"})

所以将你的 POST 修改为:

r = requests.post(
    MAILGUN_URL,
    auth=("api", MAILGUN_KEY),
    files = [("attachment", f)],
    data={
        "subject": "My subject",
        "from": "my_email@gmail.com",
        "to": "to_you@gmail.com",
        "text": "The text",
        "html": "The<br>html"
    },
    headers={'Content-type': 'multipart/form-data;'},
)

这应该适合你。