【问题标题】:Send attached file with Mailgun using python [duplicate]使用python使用Mailgun发送附件[重复]
【发布时间】:2016-10-22 06:02:39
【问题描述】:

我正在尝试使用 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")

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

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

【问题讨论】:

  • 我建议在网上做任何事情之前先检查一下documentation。如果您知道错误代码,您会立即知道在哪里寻找错误。在这种情况下:某些参数丢失或被错误地保护

标签: python python-requests multipartform-data email-attachments mailgun


【解决方案1】:

您需要使用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;'},
)

这对你应该没问题。

【讨论】:

  • 对我有用,但前提是我没有指定 headers 参数。无论如何,这似乎是自动处理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多