我使用Mailgun使用以下“ curl”命令:

curl -s --user 'api:key-xxxxxx' \
    https://api.mailgun.net/v3/sandboxyyyyyy.mailgun.org/messages \
    -F from='Excited User <[email protected]>' \
    -F [email protected] \
    -F [email protected] \
    -F subject='Hello' \
    -F text='Testing some Mailgun awesomness!'


我需要在Python中使用“ httplib”(不是请求!)来通过Mailgun发送电子邮件。如何将上述curl命令转换为要在httplib.HTTPSConnection的请求中使用的HTTP标头(“ POST”,URL,参数,标头)?

最佳答案

用法httplib没问题。

import httplib
import urllib
from base64 import b64encode

# your form
params = urllib.urlencode({'from': 'Excited User <[email protected]>',
                           'to': '[email protected]',
                           'subject': 'Hello',
                           'text': 'Testing some Mailgun awesomness!'})

# build authorization
user_and_pass = b64encode(b"username:password").decode("ascii")

# headers
headers = {'Authorization': 'Basic %s' % user_and_pass}

# connection
conn = httplib.HTTPConnection("api.mailgun.net")
conn.request('POST', '/v3/sandboxyyyyyy.mailgun.org/messages', params, headers)

# get result
response = conn.getresponse()

print response.status, response.reason

data = response.read()

conn.close()


请检查沙盒网址和参数。

另外,位于https://documentation.mailgun.com/api-sending.html#sending的文档

关于python - 将curl转换为httplib header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33929133/

10-12 17:56