def mailchimp_update_active_inactive_users_segments(): list_id = settings.MAILCHIMP_DEFAULT_LIST active_segment_id = settings.MAILCHIMP_ACTIVE_SEGMENT inactive_segment_id = settings.MAILCHIMP_INACTIVE_SEGMENT limit = 1000 actives = Customer.objects.active() inactives = Customer.objects.inactive() for i in range(0, actives.count(), limit): _actives = actives[i:i + limit] payload = [{'email': cus.user.email.lower()} for cus in _actives] try: m = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) # add active users to Active segment m.lists.static_segment_members_add( id=list_id, seg_id=active_segment_id, batch=payload, ) # remove active users from Inactive segment m.lists.static_segment_members_del( id=list_id, seg_id=inactive_segment_id, batch=payload, ) except mailchimp.Error as e: logger.error('Failed to manage active users', exc_info=True) raise self.retry(exc=e, countdown=30) for i in range(0, inactives.count(), limit): _inactives = inactives[i:i + limit] payload = [{'email': cus.user.email.lower()} for cus in _inactives] try: m = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) # add inactive users to Inactive segment m.lists.static_segment_members_add( id=list_id, seg_id=inactive_segment_id, batch=payload, ) # remove inactive users from Active segment m.lists.static_segment_members_del( id=list_id, seg_id=active_segment_id, batch=payload, ) except mailchimp.Error as e: logger.error('Failed to manage inactive users', exc_info=True) raise self.retry(exc=e, countdown=30)
def add_subscriber(email): if not MailingListService.get_is_initialized(): MailingListService.__log.warn( "CANNOT USE MAILCHIMP API. KEYS NOT SET") MailingListService.__log.warn( "Set your API keys in development.ini / production.ini") return False api = mailchimp.Mailchimp(apikey=MailingListService.mailchimp_api) if not email or not email.strip(): return False try: api.lists.subscribe(MailingListService.mailchimp_list_id, {'email': email.strip().lower()}, double_optin=False, update_existing=True, replace_interests=False) MailingListService.__log.notice( "Successfully added {} to the mailchimp list.".format(email)) return True except Exception as x: MailingListService.__log.error( "Error during mailing list signup: {}".format(x)) return False
def add_user(user, mailing_list_id=None): try: mailchimp_api = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) except mailchimp.Error: logger.error("Missing or invalid MAILCHIMP_API_KEY") return list_id = mailing_list_id or mailchimp_default_list_id if list_id is None: logger.error("Missing MAILCHIMP_LIST_ID") return try: response = mailchimp_api.lists.subscribe(list_id, {'email': user.email}, double_optin=False, update_existing=False, replace_interests=False) logger.debug("{} was successfully subscribed to list {}".format( response['email'], list_id)) except mailchimp.ListDoesNotExistError: logger.error("List {} does not exist".format(list_id)) except mailchimp.ListAlreadySubscribedError: logger.info("User already subscribed to list {}".format(list_id)) except mailchimp.Error as e: logger.error("An error occurred: {} - {}".format(e.__class__, e))
class SignUpAPITestCase(TestCase): m = mailchimp.Mailchimp() def tearDown(self): self.m.lists.batch_unsubscribe(settings.MAILCHIMP_LIST_ID, [{'email': TEST_DATA[0]['email']}], delete_member=True, send_goodbye=False) def test_sign_up_api_invalid(self): response = self.client.post(reverse('api-sign_up')) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(response['Access-Control-Allow-Origin'], '*') self.assertEqual(json.loads(response.content), {'message': 'email: This field is required.\npassword: This field is required.\nusername: This field is required.\nage: This field is required.\ncareer: This field is required.\ncity: This field is required.\ncommunity: This field is required.\ncountry: This field is required.\nfamily: This field is required.\ngender: This field is required.\nreligion: This field is required.\nself: This field is required.', 'status': 'error'}) def test_sign_up_api_valid(self): response = self.client.post(reverse('api-sign_up'), TEST_DATA[0]) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(response['Access-Control-Allow-Origin'], '*') self.assertEqual(json.loads(response.content), {'data': {'token': Profile.objects.get().token}, 'status': 'success'}) self.assertEqual(len(mail.outbox), 2) self.assertEqual(self.m.lists.members(settings.MAILCHIMP_LIST_ID)['total'], 1)
def mailchimp_subscribe(self, email, is_lead=True, merge_vars=None, **kwargs): if not email: return if not merge_vars: merge_vars = {} email = email.lower() list_id = settings.MAILCHIMP_DEFAULT_LIST leads_segment_id = settings.MAILCHIMP_LEADS_SEGMENT try: m = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) m.lists.subscribe( id=list_id, email={'email': email}, double_optin=False, update_existing=True, send_welcome=False, merge_vars=merge_vars, ) except mailchimp.Error as e: logger.error('Failed to subscribe %s', email, exc_info=True) raise self.retry(exc=e, countdown=5) else: if is_lead: mailchimp_segment_member_add.apply_async((email, leads_segment_id), countdown=20)
def get(cls, email_address): self = cls() self.email = email_address apikey = os.environ.get('MAILCHIMP_API_AWR') master_list = '1090921d49' campaigns = set() opens = set() clicks = set() mc = mailchimp.Mailchimp(apikey=apikey) email_array = [{'email': email_address}] result = mc.lists.member_activity(master_list, email_array) for action in result['data'][0]['activity']: action_type = action['action'] id = action['campaign_id'] # timestamp = action['timestamp'] # name = action['campaign_data']['subject'] if action_type == 'sent': campaigns.add(id) elif action_type == 'open': opens.add(id) elif action_type == 'click': clicks.add(id) else: print('Unknown action type = "{}"'.format(action_type)) self.campaigns = len(campaigns) self.opens = len(opens) self.clicks = len(clicks) return self
def add_customer(pCustomer): theResponse = 'This is the API to add a new customer' with session_scope() as s: the_result = s.add(pCustomer) # Determine if this new customer has elected to subscribe if (pCustomer.subscribe == 'Yes'): # Yes. Therefore post to MailChimp print('SUBSCRIBE THIS CUSTOMER!') # TODO: Move these specific values to a properties.ini file. API_KEY = '2e68df53d0457c4b9ceb25bf34cf99d8-us20' LIST_ID = '06d4e253a8' api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': pCustomer.email}) print('DONE!') except: print('ERROR!') #MAILCHIMP_SIGNUP_URL = 'https://corbinian.us20.list-manage.com/subscribe/post?u=cc1f637aebedc431bca68ebb2&id=06d4e253a8' #PARAMS = {'email':'*****@*****.**', 'b_cc1f637aebedc431bca68ebb2_06d4e253a8': ''} #try: # r = requests.post(url = MAILCHIMP_SIGNUP_URL, params = PARAMS) #except: # print('ERROR!') ## pastebin_url = r.text ## print("The pastebin URL is:%s"%pastebin_url) return the_result
def actionGetLists(self): # Buscar config mailchimp mailchimps = self.env['mailchimp.config'].search([]) if mailchimps: # Siempre conecta, pero para saber si los datos de la API o la # lista de suscripcion son correctos, necesitamos ejecutar las # siguientes funciones try: # Conectar mapi = mailchimp.Mailchimp(mailchimps[0].mapi) # Eliminar los registros de la tabla por si las listas han # cambiado mailchimp_lists = self.env['mailchimp.list'].search([]) for mailchimp_list in mailchimp_lists: mailchimp_list.unlink() # Obtener las listas de subscripcion lists = mapi.lists.list() # Crear registros de listas for l in lists['data']: data = { 'name': l['name'], } self.env['mailchimp.list'].create(data) except: raise exceptions.Warning(_('Data error Mailchimp connection.')) else: raise exceptions.Warning( _('Not exists configuration of Mailchimp in the system. ' 'Make sure you have saved the settings.'))
def post_ajax(self, request, *args, **kwargs): email = request.POST.get('email').strip().lower() mailchimp_list_id = settings.MAILCHIMP_LIST_ID response_dict = { 'message': '{0} successfully subscribed to {1}!'.format( email, mailchimp_list_id), } mc = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) try: mc.lists.subscribe( id=mailchimp_list_id, email={'email': email}, update_existing=True, double_optin=True, ) logger.info('%s successfully subscribed to %s', email, mailchimp_list_id) except mailchimp.Error as e: logger.error('A MailChimp error occurred: %s', e) response_dict['message'] = 'Sorry, an error occurred.' return self.render_json_response(response_dict, status=500) return self.render_json_response(response_dict)
def subscribe_to_newsletter(user): if settings.MAILCHIMP_NEWSLETTER_KEY: try: mc = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) mc.lists.subscribe(id=settings.MAILCHIMP_NEWSLETTER_KEY, email={'email': user.email}, send_welcome=True) except: pass
def sign_in_landing(request): user = request.user if user.newsletter and settings.COURRIERS_MAILCHIMP_API_KEY: try: m = mailchimp.Mailchimp(settings.COURRIERS_MAILCHIMP_API_KEY) m.lists.subscribe(settings.COURRIERS_MAILCHIMP_LIST, {'email': user.email}) user.newsletter = False user.save() messages.success( request, _("The email has been successfully subscribed")) except mailchimp.ListAlreadySubscribedError: messages.error( request, _("That email is already subscribed to the list")) return HttpResponseRedirect('/') except mailchimp.Error as e: log.error("mailchimp error: %s, %s", e.__class__, e) messages.error(request, _("An error occurred while subscribing" " to mailing list.")) return HttpResponseRedirect('/') if not user.greeted: user.greeted = True user.save() url = reverse('profile:credit_card_prompt') return HttpResponseRedirect(url) redirect_to = request.GET.get(REDIRECT_FIELD_NAME, '') if redirect_to: if is_safe_url(url=redirect_to, host=request.get_host()): return HttpResponseRedirect(redirect_to) return redirect('profile:my_page')
def subscribe(list_id=None): '''Adds user to Theworldphone mailing list. :param list_id: ID of Mailchimp list to subscribe user to. :type list_id: string. :returns: JSON object containing response string. :raises: mailchimp.ListAlreadySubscribedError, mailchimp.Error. ''' data = json.loads(request.data) list_id = 'bf774de909' email = data['email'] try: m = mailchimp.Mailchimp(current_app.config['MAILCHIMP_API_KEY']) if not list_id: lists = m.lists.list() if lists: list_id = lists['data'][0]['id'] m.lists.subscribe(list_id, {'email': email}) resp = "You subscribed." except mailchimp.ListAlreadySubscribedError: resp = "That email is already subscribed." except mailchimp.Error as e: resp = 'An error occurred: %s - %s' % (e.__class__, e) return jsonify({'result': resp})
def mailchimp_sync_leads_data(): customers = Customer.objects.all().values('user__email') cus_emails = [cus['user__email'].lower() for cus in customers] leads = (GetStartedResponse.objects.all().exclude( email__in=cus_emails).values('email', 'name')) list_id = settings.MAILCHIMP_DEFAULT_LIST limit = 500 for from_id in range(0, len(leads), limit): _leads = leads[from_id:from_id + limit] payload = [{ 'email': { 'email': lead['email'].lower() }, 'merge_vars': { 'FNAME': lead['name'], } } for lead in _leads] # need more merge vars? check methods: # - merge_var_add # - merge_var_update try: m = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) m.lists.batch_subscribe( id=list_id, double_optin=False, update_existing=True, batch=payload, ) except mailchimp.Error: logger.error('Failed to sync leads', exc_info=True)
def mailchimp_sync_customers_data(): customers = Customer.objects.all().values('user__email', 'first_name', 'last_name') list_id = settings.MAILCHIMP_DEFAULT_LIST limit = 500 for from_id in range(0, len(customers), limit): _customers = customers[from_id:from_id + limit] payload = [{ 'email': { 'email': cus['user__email'].lower() }, 'merge_vars': { 'FNAME': cus['first_name'], 'LNAME': cus['last_name'], } } for cus in _customers] # need more merge vars? check methods: # - merge_var_add # - merge_var_update try: m = mailchimp.Mailchimp(apikey=settings.MAILCHIMP_API_KEY) m.lists.batch_subscribe( id=list_id, double_optin=False, update_existing=True, batch=payload, ) except mailchimp.Error: logger.error('Failed to sync existing customers', exc_info=True)
def sync_mailchimp(api_key, members): """ :param api_key: :param members: :type members: list[Member] :return: list of new subscribers """ api = mailchimp.Mailchimp(api_key) # get main subscriber list data = api.lists.list() mailing_list = next(filter( lambda x: x['name'] == 'Collegiate Cyber Defense Club Newsletter', data['data'])) batch = [] for member in members: batch.append({ 'email': { 'email': member.preferred_email } }) resp = api.lists.batch_subscribe(mailing_list['id'], batch) newly_subscribed = [x['email'] for x in resp['adds']] return newly_subscribed
def get_mailchimp_api(): request = get_current_request() try: default_key = get_mailchimp_key(request) except MailChimpCredential.DoesNotExist: raise Exception(_("Check if your API key present.")) return mailchimp.Mailchimp(default_key)
def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': self.email}) except: return False
def _get_mailchimp(self): """ get the mailchip object """ try: m = mailchimp.Mailchimp(settings.MAILCHIMP['api_key']) except Exception, e: logger = logging.getLogger(__name__) logger.error('MailChimp error (%s) (%s)' % (str(e), repr(e))) m = None
def remove_from_mailchimp(email): try: m = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) m.lists.unsubscribe(settings.MAILCHIMP_LISTID, {'email': email}) except mailchimp.Error as e: s = 'add_to_mailchimp for (%s) - error : %s - %s' % (email, e.__class__, e) logger.error(s) return False
def subscribe_by_email(email): if settings.TESTING: return mailchimp_api = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) mailchimp_api.lists.subscribe(settings.MAILCHIMP_DEFAULT_LIST, {'email': email}, double_optin=False, send_welcome=False, update_existing=True)
def processLead(lead_data): subscriber_info = {} for fields in lead_data['field_data']: subscriber_info[fields['name']] = fields['values'][0] mailchimp_api = mailchimp.Mailchimp(MAILCHIMP_API_KEY) mailchimp_api.lists.subscribe(MAILCHIMP_LIST_ID, subscriber_info)
def subscribe_to_mailing_list(user_pk): # pragma: no cover user = User.objects.get(pk=user_pk) if getattr(settings, "MAILCHIMP_API_KEY", False): m = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) m.lists.subscribe( settings.MAILCHIMP_LIST, email={"email": user.email}, double_optin=False, send_welcome=False )
def beacon(request, credentials, owner): list_id = request.GET.get('list_id', 'f557548df1') email = request.GET.get('email', '') try: mc = mailchimp.Mailchimp(credentials['api_key']) mc.lists.subscribe(list_id, {"email":email}, update_existing=True) except Exception as e: pass # send to user return Response()
def member_pre_save_cb(sender, instance, raw, **kwargs): """ Subscribe or unsubscribe a user from Mailchimp. """ if raw or settings.TESTING: return try: member = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass else: if member.newsletter == instance.newsletter: return if not settings.MAILCHIMP_API_KEY: logger.warn("User changed email preference but no Mailchimp API key " "has been specified, set MAILCHIMP_API_KEY.") return mc = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) try: address = instance.primary_email.email except AttributeError: # We're not sure why the callback is firing an extra time, before # SignupView.create_account runs (when email not yet saved). return if instance.newsletter: try: mc.lists.subscribe( settings.MAILCHIMP_NEWSLETTER_LIST, {"email": address}, double_optin=False, update_existing=True, ) except mailchimp.ListAlreadySubscribedError: logger.info('"%s" was already subscribed', address) except (mailchimp.Error, ValueError) as e: logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e) else: try: mc.lists.unsubscribe( settings.MAILCHIMP_NEWSLETTER_LIST, {"email": address}, send_goodbye=False, send_notify=False, ) except (mailchimp.ListNotSubscribedError, mailchimp.EmailNotExistsError): logger.info('"%s" was already unsubscribed', address) except (mailchimp.Error, ValueError) as e: logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e)
def setup_info(request): '''tp_user = User.objects.filter(username=request.user) stripe_uid = SocialAccount.objects.filter(user=tp_user[0], provider="stripe")[0] data = stripe_uid.extra_data client = Client.objects.filter(email=data['email']) if len(client) == 0: return redirect("/pricing") client = client[0] client.pricing = request.GET["price"] client.save()''' # subscribe a price in stripe stripe.api_key = settings.STRIPE_SECRET_KEY charge = stripe.Charge.create( amount= int(request.GET["price"]) * 100, currency="usd", source=request.GET['token'], description='Sent the money!' ) client = Client.objects.filter(email=request.session['user']["email"])[0] client.pricing = int(request.GET["price"]) client.save() # subscribe in mailchimp merge_vars = { "FNAME": client.name, "PNAME": client.pet_name, "PTYPE": client.type, } if client.pricing == 29: merge_vars["GROUPINGS"] = [{ "name": "Paid", "groups":["Basic"] }] elif client.pricing == 89: merge_vars["GROUPINGS"] = [{ "name": "Paid", "groups":["Most Popular"] }] else: merge_vars["GROUPINGS"] = [{ "name": "Paid", "groups":["Premier"] }] api = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) api.lists.subscribe(settings.MAILCHIMP_LIST_ID, {"email": client.email}, merge_vars, update_existing=True) return redirect("/pricing")
def submitEmail(request): email = request.POST["email"] mailchimp_key = SECRETS_DICT["MAILCHIMP_KEY"] mailchimp_id = SECRETS_DICT["MAILCHIMP_ID"] try: mchimp = mailchimp.Mailchimp(apikey=mailchimp_key) mchimp.lists.subscribe(id=mailchimp_id, email={"email": email}) print "subscribed email: " + email except: print "error subscribing email: " + email return HttpResponse("yup")
def subscribe_user(user): mailchimp_api = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY) mailchimp_api.lists.subscribe(settings.MAILCHIMP_DEFAULT_LIST, {'email': user.email}, merge_vars={ 'FNAME': user.first_name, 'LNAME': user.last_name }, double_optin=False, send_welcome=False, update_existing=True)
def main(api_key, list_id, file_, dry_run=False): """ :param api_key: Mailchimp API key :param list_id: Mailchimp list ID to add subscribers to :param file_: File to read subscribers from :param dry_run: Do a dry run and print the import data without importing :returns: None """ mc = mailchimp.Mailchimp(api_key) return add_subscribers_from_file(mc, list_id, file_, dry_run)
def add_to_mailchimp(list_id, email, data=None): mc = mailchimp.Mailchimp(settings.MAILCHIMP_KEY) try: return mc.lists.subscribe( list_id, {'email': email}, data, None, False) except mailchimp.ListAlreadySubscribedError: return False
def list(self, request, credentials): mc = mailchimp.Mailchimp(credentials['api_key']) result = mc.lists.list() results = map(lambda item: {'id': item['id'], 'title': item['name']}, result['data'] ) return Response({ 'count': len(results), 'results': results, 'next': None, 'previous': None })