Skip to content
This repository has been archived by the owner on Sep 1, 2021. It is now read-only.

Add Python POST examples #32

Open
wants to merge 26 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions python/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@

class MailChimpConfig:
def __init__(self):
if os.path.isfile('../APIKEY') == False:
if os.path.isfile('APIKEY') == False:
print "Please enter your API Key into the APIKEY file as mentioned in README.md"
sys.exit()

f = open('../APIKEY', 'r+')
f = open('APIKEY', 'r+')
apikey = f.read().strip()
f.close()

parts = apikey.split('-')
if len(parts) != 2:
print "This doesn't look like an API Key: " + apikey
print "The API Key should have both a key and a server name, separated by a dash, like this: abcdefg8abcdefg6abcdefg4-us1"
sys.exit()

self.apikey = apikey
self.shard = parts[1]
self.api_root = "https://" + self.shard + ".api.mailchimp.com/3.0/"
57 changes: 57 additions & 0 deletions python/create_campaign.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# This example shows a basic POST request to create a new campaign
# See below, there are several variables you need to update

import requests # Need to install
import json
from config import MailChimpConfig

config = MailChimpConfig()

path = 'campaigns'
endpoint = config.api_root + path

# Create metadata for campaign
# See: http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/
meta = {}

meta['recipients'] = {
# Insert recipient list ID here
# See: Lists > Settings > List name and campaign defaults for ID
'list_id': 'ABCDE12345'
}

meta['settings'] = {
'subject_line': 'New product announcement!', # Subject line
'from_name': 'Your company', # From name
'title': '1/1/16: New product', # Campaign title
'inline_css': True, # Automatically inline CSS
'fb_comments': False, # Facebook comments
'auto_footer': False, # Auto MailChimp footer
'to_name': '*|FNAME|* *|LNAME|*', # To name (See merge tag cheat sheet: http://kb.mailchimp.com/merge-tags/all-the-merge-tags-cheat-sheet)
'folder_id': '', # Put campaign in folder
'reply_to': '[email protected]', # Reply-to email
'auto_tweet': False, # Auto tweet newsletter
}

meta['type'] = 'regular' # Campaign type

#print meta

# JSON-ify metadata
payload = json.dumps(meta)

#print payload

# Send post request
response = requests.post(endpoint, auth=('apikey', config.apikey), data=payload)

#print response.json()

try:
response.raise_for_status()
body = response.json()
id = body['id']
# Print out new campaign ID to do something else with it (like set content)
print id
except requests.exceptions.HTTPError as err:
print "\n\n\nError: %s" % err
53 changes: 53 additions & 0 deletions python/folders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
""" This example demonstrates showing some basic details about your folders
Below you can see examples of pagination as well as partial response
"""

import requests
import json
try:
import urlparse
except ImportError:
from urllib import parse as urlparse
from config import MailChimpConfig


config = MailChimpConfig()

endpoint = urlparse.urljoin(config.api_root, 'campaign-folders')
params = {
# With Partial Response, you choose which fields you want to see
'fields': 'folders.id,folders.name,folders.stats.member_count',
# Pagination in API v3.0 is always done with count and offset
'count': 10, 'offset': 0
}

total_folders = 0

while True:
response = requests.get(endpoint, auth=('apikey', config.apikey),
params=params, verify=False)

try:
response.raise_for_status()
body = response.json()
except requests.exceptions.HTTPError as err:
print "Error: {} {}".format(str(response.status_code), err)
print json.dumps(response.json(), indent=4)
break
except ValueError:
print "Cannot decode json, got %s" % response.text
break

if len(body['folders']) == 0:
break

total_folders += len(body['folders'])

for folder in body['folders']:
print u'%s: %s' % (
folder['id'],
folder['name'])

params['offset'] += params['count']

print "\n" + str(total_folders) + " folders found."
1 change: 1 addition & 0 deletions python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests==2.11.0
28 changes: 28 additions & 0 deletions python/test_email.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This example shows a basic POST request that sends a test email.

import requests # Need to install
import json
from config import MailChimpConfig

config = MailChimpConfig()

# Set your variables here
campaign_id = 'ABCD1234' # INSERT CAMPAIGN ID HERE
test_email = ["[email protected]"] # INSERT TEST EMAIL HERE

test = "campaigns/{0}/actions/test".format(campaign_id)
endpoint = config.api_root + test

payload = json.dumps({'test_emails': test_email, 'send_type': 'html'})

#print "\nPayload: " + payload

response = requests.post(endpoint, auth=('apikey', config.apikey), data=payload)

#print "\nURL: " + response.url + "\n\n"

try:
response.raise_for_status()
print "\n\n Test sent \n\n"
except requests.exceptions.HTTPError as err:
print '\n\n\nError: %s' % err