2

I have the following "curl" command working with 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!'

I need to use "httplib" (not requests!) in Python to send emails with Mailgun. How to convert the curl command as above to HTTP headers to be used in httplib.HTTPSConnection's request('POST', URL, params, headers)?

alextc
  • 3,206
  • 10
  • 63
  • 107

1 Answers1

1

Usage httplib is not a problem.

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()

Please check-up sandbox url and params.

Also, docs available at https://documentation.mailgun.com/api-sending.html#sending

mrDinkelman
  • 488
  • 1
  • 9
  • 18