使用Python通过Mailgun发送附件文件[重复]

问题描述 投票:0回答:1

我正在尝试使用 requests.post 通过 Mailgun API 发送带有附件的电子邮件。

在他们的文档中,他们警告说发送附件时必须使用多部分/表单数据编码,我正在尝试这样做:

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": "[email protected]",
            "to": "[email protected]",
            "text": "The text",
            "html": "The<br>html",
            "attachment": f
        },
        headers={'Content-type': 'multipart/form-data;'},
    )

    f.close()

    return r


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

我已经定义了标头以确保内容类型为 multipart/form-data,但是当我运行代码时,我得到 400 状态,原因是:错误请求

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

python python-requests multipartform-data email-attachments mailgun
1个回答
24
投票

您需要使用

files
关键字参数。 这里是请求中的文档。

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": "[email protected]",
              "cc": "[email protected]",
              "bcc": "[email protected]",
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!",
              "html": "<html>HTML version of the body</html>"})

因此将您的帖子修改为:

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

这应该适合你。


关于

headers
arg 的快速说明:

在请求中指定

headers
对于
requests
和 Mailgun 来说都完全没问题。事实上,标头是在 Mailgun 文档中的第一个示例中设置的。

也就是说,如果您选择发送标头,则应该注意一些注意事项。来自

requests
文档(强调我的):

注意:自定义标头的优先级低于更具体的信息源。例如:

如果在 .netrc 中指定了凭据,则使用 headers= 设置的授权标头将被覆盖,而该凭据又将被 auth= 参数覆盖。请求将在 ~/.netrc、~/_netrc 或 NETRC 环境变量指定的路径中搜索 netrc 文件。

如果您被重定向到脱离主机,授权标头将被删除。

代理授权标头将被 URL 中提供的代理凭据覆盖。

当我们可以确定内容的长度时,Content-Length 标头将被覆盖。

此外,Requests 根本不会根据指定的自定义标头更改其行为。标头只是传递到最终请求中。

© www.soinside.com 2019 - 2024. All rights reserved.