小编mao*_*aiz的帖子

使用python使用Mailgun发送附件

我正在尝试使用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")
Run Code Online (Sandbox Code Playgroud)

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

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

python multipartform-data email-attachments python-requests mailgun

6
推荐指数
1
解决办法
3800
查看次数