1 from hashlib import md5
3 from django.conf import settings
4 from mailchimp3 import MailChimp
5 from mailchimp3.mailchimpclient import MailChimpError
8 def subscriber_hash(email):
9 return md5(email.encode('utf-8')).hexdigest()
12 def remove_from_groups(email, client):
14 categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
15 for category in categories:
16 groups = client.lists.interest_categories.interests.all(
17 list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
18 group_ids += [group['id'] for group in groups]
19 interests = {group_id: False for group_id in group_ids}
20 client.lists.members.update(
21 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
22 data={'interests': interests})
25 def subscribe(email, mailing_lists=None):
26 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
28 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
29 except MailChimpError:
32 if member['status'] != 'subscribed':
33 remove_from_groups(email, client)
34 mailing_lists = mailing_lists or [settings.MAILCHIMP_DEFAULT_GROUP]
36 settings.MAILCHIMP_GROUP_IDS[mailing_list]: True
37 for mailing_list in mailing_lists
38 if mailing_list in settings.MAILCHIMP_GROUP_IDS
40 client.lists.members.create_or_update(
41 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
43 'email_address': email,
44 'status_if_new': 'subscribed',
45 'status': 'subscribed',
46 'interests': interests,
51 def unsubscribe(email, mailing_lists=None):
52 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
54 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
55 except MailChimpError:
58 if member['status'] != 'subscribed':
60 mailing_lists = mailing_lists or settings.MAILCHIMP_GROUP_IDS
62 settings.MAILCHIMP_GROUP_IDS[mailing_list]: False
63 for mailing_list in mailing_lists
64 if mailing_list in settings.MAILCHIMP_GROUP_IDS
66 client.lists.members.update(
67 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
69 'interests': interests,