From 14c183c7aecfdf240eb54fbaa659588e940535de Mon Sep 17 00:00:00 2001 From: Jan Szejko Date: Tue, 27 Nov 2018 13:59:32 +0100 Subject: [PATCH] unsubscribe from mailchimp --- src/contact/mailing.py | 23 +++++++++++++++++++++++ src/newsletter/forms.py | 1 + 2 files changed, 24 insertions(+) diff --git a/src/contact/mailing.py b/src/contact/mailing.py index 2034766cd..2d578e66d 100644 --- a/src/contact/mailing.py +++ b/src/contact/mailing.py @@ -48,3 +48,26 @@ def subscribe(email, mailing_lists=None): 'interests': interests, } ) + + +def unsubscribe(email, mailing_lists=None): + client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0) + try: + member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email)) + except MailChimpError: + return + else: + if member['status'] != 'subscribed': + return + mailing_lists = mailing_lists or settings.MAILCHIMP_GROUP_IDS + interests = { + settings.MAILCHIMP_GROUP_IDS[mailing_list]: False + for mailing_list in mailing_lists + if mailing_list in settings.MAILCHIMP_GROUP_IDS + } + client.lists.members.update( + settings.MAILCHIMP_LIST_ID, subscriber_hash(email), + data={ + 'interests': interests, + } + ) diff --git a/src/newsletter/forms.py b/src/newsletter/forms.py index 8cb19ee19..d473cf3a8 100644 --- a/src/newsletter/forms.py +++ b/src/newsletter/forms.py @@ -82,6 +82,7 @@ class UnsubscribeForm(Form): subscription = self.cleaned_data['subscription'] subscription.active = False subscription.save() + mailing.unsubscribe(subscription.email) context = {'subscription': subscription} # refactor to send_noreply_mail -- 2.20.1