将curl转换为httplib标头

时间:2015-11-26 01:16:59

标签: python curl mailgun httplib

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

curl -s --user 'api:key-xxxxxx' \
    https://api.mailgun.net/v3/sandboxyyyyyy.mailgun.org/messages \
    -F from='Excited User <mailgun@sandboxyyyyyy.mailgun.org>' \
    -F to=ToEmail1@domain.com \
    -F to=ToEmail2@domain.com \
    -F subject='Hello' \
    -F text='Testing some Mailgun awesomness!'

我需要在Python中使用“httplib”(不是请求!)来发送带有Mailgun的电子邮件。如何将curl命令转换为HTTP头文件,以便在httplib.HTTPSConnection的请求中使用('POST',URL,params, header )?

1 个答案:

答案 0 :(得分:1)

用法httplib不是问题。

import httplib
import urllib
from base64 import b64encode

# your form
params = urllib.urlencode({'from': 'Excited User <mailgun@sandboxyyyyyy.mailgun.org>',
                           'to': 'ToEmail1@domain.com',
                           '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