1 # -*- coding: utf-8 -*-
3 from hashlib import md5
6 from django.conf import settings
7 from mailchimp3 import MailChimp
8 from mailchimp3.mailchimpclient import MailChimpError
10 INTERESTS = {settings.MAILCHIMP_GROUP_ID: True}
14 headers = requests.utils.default_headers()
15 headers['User-Agent'] = '%s (%s)' % settings.MANAGERS[0]
18 def subscriber_hash(email):
19 return md5(email).hexdigest()
22 def remove_from_groups(email, client):
24 categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
25 for category in categories:
26 groups = client.lists.interest_categories.interests.all(
27 list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
28 group_ids += [group['id'] for group in groups]
29 interests = {group_id: False for group_id in group_ids}
30 client.lists.members.update(
31 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
32 data={'interests': interests})
36 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
38 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
39 except MailChimpError:
42 if member['status'] != 'subscribed':
43 remove_from_groups(email, client)
44 client.lists.members.create_or_update(
45 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
47 'email_address': email,
48 'status_if_new': 'subscribed',
49 'status': 'subscribed',
50 'interests': INTERESTS,