def add_and_update_cm_subscribers(list_id, subscribers): ''' Adds new people to a Campaign Monitor list, and updates fields of existing subscribers. (If a field is ommited, its value remains unchanged.) ''' logger.info("Adding new and updating existing.") subscriber = Subscriber(settings.CAMPAIGN_MONITOR_AUTH) import_result = subscriber.import_subscribers(list_id, subscribers, False) logger.info("Added new and updated existing.") report = { "new_subscribers": import_result.TotalNewSubscribers, "existing_subscribers": import_result.TotalExistingSubscribers, "duplicates_in_import_list": import_result.DuplicateEmailsInSubmission, "uniques_in_import_list": import_result.TotalUniqueEmailsSubmitted } if len(import_result.FailureDetails): errors = defaultdict(list) for error in import_result.FailureDetails: errors["{} ({})".format(error.Message, error.Code)].append(error.EmailAddress) report["errors"] = errors return report
def resubscribe(self): cs = CreateSend( {"api_key": Configuration.instance.get_setting("campaign_monitor_api_key")} ) now = datetime.now() for client in cs.clients(): client = Client( {"api_key": Configuration.instance.get_setting("campaign_monitor_api_key")}, client.ClientID ) for list in client.lists(): subscriber = Subscriber( {"api_key": Configuration.instance.get_setting("campaign_monitor_api_key")} ) try: response = subscriber.get(list.ListID, self.email) except BadRequest: continue date = datetime.strptime(response.Date, '%Y-%m-%d %H:%M:%S') diff = now - date if response.State != "Active" and ( date > now or diff.seconds < self.max_seconds ): response = subscriber.add( list.ListID, self.email, response.Name, None, True ) self.resubscribed_lists.append(list.ListID)
def unsubscribe_cm_subscribers(list_id, emails): ''' Unsubscribes all passed-in email addresses from a specified Campaign Monitor list. ''' logger.info("Begin unsubscribing people from list {}".format(list_id)) unsubscribed = [] for email in emails: subscriber = Subscriber(settings.CAMPAIGN_MONITOR_AUTH, list_id, email) subscriber.unsubscribe() unsubscribed.append(email) logger.info("Done unsubscribing people from list {}".format(list_id)) return unsubscribed
def update_subscription(profile, old_email): """ Update a profile subscription on campaign monitor. If the old email is not on CM this will not subscribe the user to CM. """ if api_key and client_id: user = profile.user for group in profile.get_groups(): for listmap in group.listmap_set.all(): subscriber = Subscriber(auth, listmap.list_id, old_email) try: subscriber.update(user.email, user.get_full_name(), [], False) except BadRequest as e: print(e)
def sync_cm_subscriber(sender, instance=None, created=False, **kwargs): """Subscribe the subscriber to the campaign monitor list """ (name, email) = get_name_email(instance) if email: add_list = True add_subscriber = True list_map = None try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id list = List(list_id) if list: subscriber_obj = Subscriber(list_id) try: list_stats = list.stats() #print 'number active:', list_stats.TotalActiveSubscribers add_list = False # at this stage, we're sure the list is ON the C. M. # check if this user has already subscribed, if not, subscribe it try: subscriber = subscriber_obj.get(list_id, email) if str(subscriber.State).lower == 'active': add_subscriber = False except BadRequest as br: pass except Unauthorized as e: list = List() except ListMap.DoesNotExist: list = List() if add_list: # this list might be deleted on campaign monitor, add it back list_id = list.create(cm_client_id, instance.group.name, "", False, "") subscriber_obj = Subscriber(list_id) if not list_map: list_map = ListMap() list_map.group = instance.group list_map.list_id = list_id list_map.save() if add_subscriber: email_address = subscriber_obj.add(list_id, email, name, [], True)
def add_subscriber(self, list): subscriber = Subscriber({ "api_key": Configuration.instance.get_setting("x_campaign3_api_key") }) # Check if the user is new to any list try: response = subscriber.get(list.list_id, self.email) except BadRequest: self.is_new = True else: if response.State != "Active": self.is_new = True response = subscriber.add(list.list_id, self.email, self.name, self.custom_fields, True)
def delete_cm_subscriber(sender, instance=None, **kwargs): """Delete the subscriber from the campaign monitor list """ (name, email) = get_name_email(instance) if email: try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id list = List(list_id) if list: subscriber_obj = Subscriber(list_id, email) try: subscriber_obj.unsubscribe() except: pass except ListMap.DoesNotExist: pass
def delete_cm_subscriber(sender, instance=None, **kwargs): """Delete the subscriber from the campaign monitor list """ from django.core.validators import email_re (name, email) = get_name_email(instance) if email and email_re.match(email): try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id list = List(list_id) if list: subscriber_obj = Subscriber(list_id, email) try: subscriber_obj.unsubscribe() except: pass except ListMap.DoesNotExist: pass
def capture_email(): success = False errors = {} if request.method == "POST" and 'honeypot' in request.form and len(request.form['honeypot']) < 1 and 'email' in request.form: if 'email' in request.form and len(request.form['email'])>0: session['email'] = request.form['email'] if len(request.form['name'])>0 and session['name'] is not None and request.form['name'].upper() == session['name'].upper(): user = User.query.filter_by(name=session['name']).first() user.email = request.form('email') else: create_user(request.form['email'],request.form['name']) save_answer() sub = Subscriber() sub.add(campaign_monitor_list_id,request.form['email'],request.form['name'],[],True) success = True else: errors['email'] = 'we need an email to keep in touch' if request.method == "POST" and 'ajax' in request.form: return render_template('email_question.html',success=success,form=request.form,errors={}) update_session_question('email',{'success':success,'errors':errors}) return redirect("/#email_question")
def delete_cm_subscriber(sender, instance=None, **kwargs): """Delete the subscriber from the campaign monitor list """ from tendenci.apps.base.utils import validate_email (name, email) = get_name_email(instance) if email and validate_email(email): try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id alist = List(auth, list_id) if alist: subscriber_obj = Subscriber(auth, list_id, email) try: subscriber_obj.unsubscribe() except: pass except ListMap.DoesNotExist: pass
def sync_cm_subscriber(sender, instance=None, created=False, **kwargs): """Subscribe the subscriber to the campaign monitor list Check if sync_newsletters is True. Do nothing if False. """ from django.core.validators import email_re if instance and instance.group and not instance.group.sync_newsletters: return (name, email) = get_name_email(instance) if email and email_re.match(email): add_list = False add_subscriber = True list_map = None # Append custom fields from the profile profile = None if hasattr(instance, 'member'): profile = instance.member.profile custom_data = [] if profile: fields = ['city', 'state', 'zipcode', 'country', 'sex', 'member_number'] for field in fields: data = {} data['Key'] = field data['Value'] = getattr(profile, field) if not data['Value']: data['Clear'] = True custom_data.append(data) try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id list = List(list_id) if list: # subscriber setup subscriber_obj = Subscriber(list_id) try: list_stats = list.stats() # check if this user has already subscribed, if not, subscribe it try: subscriber = subscriber_obj.get(list_id, email) if str(subscriber.State).lower() == 'active': subscriber = subscriber_obj.update(email, name, custom_data, True) add_subscriber = False except BadRequest as br: pass except Unauthorized as e: list = List() add_list = True except ListMap.DoesNotExist: list = List() add_list = True try: if add_list: # this list might be deleted on campaign monitor, add it back list_id = list.create(cm_client_id, instance.group.name, "", False, "") # custom fields setup setup_custom_fields(list) subscriber_obj = Subscriber(list_id) if not list_map: list_map = ListMap() list_map.group = instance.group list_map.list_id = list_id list_map.save() if add_subscriber: email_address = subscriber_obj.add(list_id, email, name, custom_data, True) except BadRequest as br: pass
def sync_cm_subscriber(sender, instance=None, created=False, **kwargs): """Subscribe the subscriber to the campaign monitor list """ from django.core.validators import email_re (name, email) = get_name_email(instance) if email and email_re.match(email): add_list = False add_subscriber = True list_map = None # Append custom fields from the profile profile = None if hasattr(instance, 'member'): profile = instance.member.profile custom_data = [] if profile: fields = ['city', 'state', 'zipcode', 'country', 'sex', 'member_number'] for field in fields: data = {} data['Key'] = field data['Value'] = getattr(profile, field) if not data['Value']: data['Clear'] = True custom_data.append(data) try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id list = List(list_id) if list: # subscriber setup subscriber_obj = Subscriber(list_id) try: list_stats = list.stats() # check if this user has already subscribed, if not, subscribe it try: subscriber = subscriber_obj.get(list_id, email) if str(subscriber.State).lower() == 'active': subscriber = subscriber_obj.update(email, name, custom_data, True) add_subscriber = False except BadRequest as br: pass except Unauthorized as e: list = List() add_list = True except ListMap.DoesNotExist: list = List() add_list = True try: if add_list: # this list might be deleted on campaign monitor, add it back list_id = list.create(cm_client_id, instance.group.name, "", False, "") # custom fields setup setup_custom_fields(list) subscriber_obj = Subscriber(list_id) if not list_map: list_map = ListMap() list_map.group = instance.group list_map.list_id = list_id list_map.save() if add_subscriber: email_address = subscriber_obj.add(list_id, email, name, custom_data, True) except BadRequest as br: pass
for c in country_list: print(c) ''' #for t in tz_list: # print(t) my_list = List(account_auth) #my_list.create("9cde80d058d8e4955a076d33b6ec2294", "July 13 v8", "", False, "") #print(my_list.list_id) my_subscriber = Subscriber(a_test_client_auth) ''' my_custom_fields = [{"Key": "Favorite Cuisine", "Value": "Pizza"},{'Key': 'Hobby', "Value": "Football"}] new_custom_fields = [{"Key": "things i love", "Value": "new york"}, {"Key": "things i also love", "Value": "coding"}, {"Key": "things i hate", "Value": "watching tv"}] #my_subscriber.add("5926ac888cffa2665144bae9127a89a5", "*****@*****.**", "Subscriber", my_custom_fields, True, "yes") my_subscriber.add("5926ac888cffa2665144bae9127a89a5", "*****@*****.**", "Subscriber", new_custom_fields, True, "yes") ''' subscribers = [{"EmailAddress":"*****@*****.**","Name":"New Subscriber One","CustomFields":[{"Key":"website","Value":"http://example.com"},{"Key":"interests","Value":"magic"},{"Key":"interests","Value":"romantic walks"},{"Key":"age","Value":"","Clear":True}],"ConsentToTrack":"Yes"},{"EmailAddress":"*****@*****.**","Name":"New Subscriber Two","ConsentToTrack":"No"},{"EmailAddress":"*****@*****.**","Name":"New Subscriber Three","ConsentToTrack":"Unchanged"}] #my_subscriber.import_subscribers("5926ac888cffa2665144bae9127a89a5", subscribers, True, False, True)
def sync_cm_subscriber(sender, instance=None, created=False, **kwargs): """Subscribe the subscriber to the campaign monitor list Check if sync_newsletters is True. Do nothing if False. """ from tendenci.apps.base.utils import validate_email from tendenci.apps.profiles.models import Profile if instance and instance.group and not instance.group.sync_newsletters: return (name, email) = get_name_email(instance) if email and validate_email(email): add_list = False add_subscriber = True list_map = None # Append custom fields from the profile profile = None if hasattr(instance, 'member'): try: profile = instance.member.profile except Profile.DoesNotExist: profile = None custom_data = [] if profile: fields = ['city', 'state', 'zipcode', 'country', 'sex', 'member_number'] for field in fields: data = {} data['Key'] = field data['Value'] = getattr(profile, field) if not data['Value']: data['Clear'] = True custom_data.append(data) try: list_map = ListMap.objects.get(group=instance.group) list_id = list_map.list_id alist = List(auth, list_id) if alist: # subscriber setup subscriber_obj = Subscriber(auth, list_id) try: # check if this user has already subscribed, if not, subscribe it try: subscriber = subscriber_obj.get(list_id, email) if str(subscriber.State).lower() == 'active': subscriber = subscriber_obj.update(email, name, custom_data, True) add_subscriber = False except BadRequest: pass except Unauthorized: alist = List(auth) add_list = True except ServerError: pass except ListMap.DoesNotExist: alist = List(auth) add_list = True try: if add_list: # this list might be deleted on campaign monitor, add it back list_id = alist.create(cm_client_id, instance.group.name, "", False, "") # custom fields setup setup_custom_fields(alist) subscriber_obj = Subscriber(auth, list_id) if not list_map: list_map = ListMap() list_map.group = instance.group list_map.list_id = list_id list_map.save() if add_subscriber: subscriber_obj.add(list_id, email, name, custom_data, True) # Returns email_address except BadRequest: pass
def add_subscriber(username): my_subscriber = Subscriber(client_auth) custom_fields = [{"Key": 'username', "Value": username}] my_subscriber.add("7c480b336839fbba731ca50c5d269666", "*****@*****.**", username, custom_fields, True, "yes") print("success")
def handle(self, *args, **options): from tendenci.apps.user_groups.models import Group from tendenci.apps.profiles.models import Profile from tendenci.addons.campaign_monitor.models import ( ListMap, Campaign, Template, setup_custom_fields) from tendenci.addons.campaign_monitor.utils import sync_campaigns, sync_templates from createsend import (CreateSend, Client, List, Subscriber, BadRequest, Unauthorized) verbosity = 1 if 'verbosity' in options: verbosity = options['verbosity'] def subscribe_to_list(subscriber_obj, list_id, name, email, custom_data): # check if this user has already subscribed, if not, subscribe it try: subscriber = subscriber_obj.get(list_id, email) if str(subscriber.State).lower() == 'active': print name, email, ' - UPDATED' subscriber = subscriber_obj.update(email, name, custom_data, True) except BadRequest as br: print br try: email_address = subscriber_obj.add(list_id, email, name, custom_data, True) if verbosity >= 2: print "%s (%s)" % (name, email) except BadRequest as br: print name, email, ' - NOT ADDED: %s' % br api_key = getattr(settings, 'CAMPAIGNMONITOR_API_KEY', None) client_id = getattr(settings, 'CAMPAIGNMONITOR_API_CLIENT_ID', None) #CreateSend.api_key = api_key auth = {'api_key': api_key} cl = Client(auth, client_id) lists = cl.lists() list_ids = [list.ListID for list in lists] list_names = [list.Name for list in lists] list_ids_d = dict(zip(list_names, list_ids)) groups = Group.objects.filter(status=1, status_detail='active', sync_newsletters=1) listmaps = ListMap.objects.filter(group__sync_newsletters=1) syncd_groups = [listmap.group for listmap in listmaps] cm_list = List(auth) print "Starting to sync groups with campaign monitor..." print for group in groups: if group not in syncd_groups: # get the list id or create a list if not exists # campaing monitor requires the list title if group.name in list_names: list_id = list_ids_d[group.name] else: # add group to the campaign monitor list_id = cm_list.create(client_id, group.name, "", False, "") print "Added group '%s' to the C.M. list." % group.name print # insert to the listmap list_map = ListMap(group=group, list_id=list_id) list_map.save() else: list_map = ListMap.objects.filter(group=group)[0] list_id = list_map.list_id # if a previous added list is deleted on campaign monitor, add it back # TODO: we might need a setting to decide whether we want to add it back or not. a_list = List(list_id) try: list_stats = a_list.stats() # set up custom fields print "Setting up custom fields..." setup_custom_fields(a_list) #num_unsubscribed = list_stats.TotalUnsubscribes #if num_unsubscribed > 0: # # a list of all unsubscribed # unsubscribed_obj = a_list.unsubscribed('2011-5-1') # unsubscribed_emails = [res.EmailAddress for res in unsubscribed_obj.Results] # unsubscribed_names = [res.Name for res in unsubscribed_obj.Results] # unsubscribed_list = zip(unsubscribed_emails, unsubscribed_names) except Unauthorized as e: if 'Invalid ListID' in e: # this list might be deleted on campaign monitor, add it back list_id = cm_list.create(client_id, group.name, "", False, "") # update the list_map list_map.list_id = list_id list_map.save() # sync subscribers in this group print "Subscribing users to the C.M. list '%s'..." % group.name members = group.members.all() for i, member in enumerate(members, 1): # Append custom fields from the profile try: profile = member.profile except Profile.DoesNotExist: profile = None custom_data = [] if profile: fields = [ 'city', 'state', 'zipcode', 'country', 'sex', 'member_number' ] for field in fields: data = {} data['Key'] = field data['Value'] = getattr(profile, field) if not data['Value']: data['Clear'] = True custom_data.append(data) email = member.email name = member.get_full_name() subscriber_obj = Subscriber(auth, list_id, email) subscribe_to_list(subscriber_obj, list_id, name, email, custom_data) print 'Done' print 'Starting to sync campaigns with campaign monitor...' sync_campaigns() print "Done" print 'Syncing templates...' sync_templates() print "Done"
random_subscriber={} subscriber_list=[] test_field_name="Main Hobby" possible_interests=["getting drunk","playing cards","rollerblading"] #fields_created = create_custom_fields(field_name=test_field_name,options=possible_interests) #print("You created the following entry" + fields_created) #NEED TO CREATE THE CUSTOM FIELDS first for i in my_names['results']: print(i['name']['first']+" "+i['name']['last']) random_subscriber={} random_subscriber.update(Name = i['name']['first']+" "+i['name']['last']) random_subscriber.update(EmailAddress = i['email']) random_subscriber.update(ConsentToTrack = "Yes") random_subscriber.update(CustomFields = [{"Value":random.choice(possible_interests),"Key":test_field_name}]) #print(random_subscriber) subscriber_list.append(random_subscriber) #print(subscriber_list) #create_new_list(clientid="9cde80d058d8e4955a076d33b6ec2294") print(subscriber_list) my_subscriber = Subscriber(account_auth) my_subscriber.import_subscribers("2345accabd471c4c45e5fc463c8353a1", subscriber_list, True, False, True)