mao*_*aiz 6 python multipartform-data email-attachments python-requests 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并正确使用附件参数
Tha*_*Guy 13
您需要使用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": "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>"})
Run Code Online (Sandbox Code Playgroud)
所以修改你的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;'},
)
Run Code Online (Sandbox Code Playgroud)
这应该对你有用.