1 # -*- coding: utf-8 -*-
3 from hashlib import md5
5 from django.conf import settings
6 from mailchimp3 import MailChimp
7 from mailchimp3.mailchimpclient import MailChimpError
10 def subscriber_hash(email):
11 return md5(email).hexdigest()
14 def remove_from_groups(email, client):
16 categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
17 for category in categories:
18 groups = client.lists.interest_categories.interests.all(
19 list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
20 group_ids += [group['id'] for group in groups]
21 interests = {group_id: False for group_id in group_ids}
22 client.lists.members.update(
23 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
24 data={'interests': interests})
27 def subscribe(email, mailing_lists=None):
28 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
30 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
31 except MailChimpError:
34 if member['status'] != 'subscribed':
35 remove_from_groups(email, client)
36 mailing_lists = mailing_lists or [settings.MAILCHIMP_DEFAULT_GROUP]
38 settings.MAILCHIMP_GROUP_IDS[mailing_list]: True
39 for mailing_list in mailing_lists
40 if mailing_list in settings.MAILCHIMP_GROUP_IDS
42 client.lists.members.create_or_update(
43 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
45 'email_address': email,
46 'status_if_new': 'subscribed',
47 'status': 'subscribed',
48 'interests': interests,
53 def unsubscribe(email, mailing_lists=None):
54 client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
56 member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
57 except MailChimpError:
60 if member['status'] != 'subscribed':
62 mailing_lists = mailing_lists or settings.MAILCHIMP_GROUP_IDS
64 settings.MAILCHIMP_GROUP_IDS[mailing_list]: False
65 for mailing_list in mailing_lists
66 if mailing_list in settings.MAILCHIMP_GROUP_IDS
68 client.lists.members.update(
69 settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
71 'interests': interests,