def _makeusers(): """ Helper function to create user accounts. Meant for one-time user only. """ if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) else: mc = None for p in Participant.query.all(): if p.approved: # Make user, but don't make account active user = makeuser(p) if mc is not None: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter, 'PRIVATEKEY': user.privatekey, 'UID': user.uid}, double_optin = False, update_existing = True ) db.session.commit()
def add_email_to_mailchimp(sender, instance, created, **kwargs): # Check first if the mailchimp key is present. if not hasattr(settings, 'DJLANDING_MAILCHIMP_API'): logging.info('MailChimp API not present') return mailchimp_api = settings.DJLANDING_MAILCHIMP_API # Check for mailchimp list. if not hasattr(settings, 'DJLANDING_MAILCHIMP_LIST'): logging.error('MailChimp List not defined') return mailchimp_list = settings.DJLANDING_MAILCHIMP_LIST # Subscribe user to list. mc = MailChimp(mailchimp_api) try: mc.listSubscribe( id=mailchimp_list, email_address=instance.email, merge_vars={'EMAIL': instance.email}, double_optin=False) except Exception, e: logging.error(e) logging.error("Trying to add email: %s." % (instance.email, ))
def signup(request): title = "Newsletter Sign Up" form = NewsletterSignupForm() if request.method == "POST": form.update(request.POST,request.FILES) if form.is_valid(): request.session['user_email'] = form.cleaned["email"] # submit to mailchimp mc = MailChimp('279d12598a1af566db37d6bb1c2e77bc-us7') lists = mc.lists() list_id = lists[0]['id'] try: mc.listSubscribe( id=list_id, email_address=form.cleaned['email'], send_welcome=False, replace_interests=False, update_existing=False, merge_vars={'EMAIL': form.cleaned['email']}, double_optin=False) except MailChimpError, e: pass #raise Exception("\n%s : mailchimp error: %s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e.msg, e.code )) #open("/usr/local/web/logs/mailchimp.log","a+").write("\n%s : mailchimp error: %s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e.msg, e.code )) return HttpResponseRedirect("/?msg=1")
def admin_approve(key): if key and key in app.config['ACCESSKEY_APPROVE']: p = Participant.query.get(request.form['id']) if not p: status = "No such user" else: if 'action.undo' in request.form: p.approved = False status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: p.approved = True status = "Tada!" mailsent = False # 1. Make user account and activate it user = makeuser(p) user.active = True # 2. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter, 'PRIVATEKEY': user.privatekey, 'UID': user.uid}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 3. Send notice of approval if not mailsent: msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice.md", p=p) msg.html = markdown(msg.body) with app.open_resource("static/doctypehtml5.ics") as ics: msg.attach("doctypehtml5.ics", "text/calendar", ics.read()) mail.send(msg) db.session.commit()
def approve(key): if key and key in app.config['ACCESSKEY_APPROVE']: p = Participant.query.get(request.form['id']) if not p: status = 'No such user' else: if 'action.undo' in request.form: p.approved = False status = 'Undone!' # Remove from MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listUnsubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, send_goodbye = False, send_notify = False, ) pass except MailChimpError, e: status = e.msg db.session.commit() elif 'action.approve' in request.form: p.approved = True status = "Tada!" mailsent = False # 1. Add to MailChimp if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']: mc = MailChimp(app.config['MAILCHIMP_API_KEY']) try: mc.listSubscribe( id = app.config['MAILCHIMP_LIST_ID'], email_address = p.email, merge_vars = {'FULLNAME': p.fullname, 'JOBTITLE': p.jobtitle, 'COMPANY': p.company, 'TWITTER': p.twitter}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 2. Send notice of approval if not mailsent: msg = Message(subject="Your registration has been approved", recipients = [p.email]) msg.body = render_template("approve_notice.md", p=p) msg.html = markdown(msg.body) mail.send(msg) db.session.commit()
class Mail(object): def __init__(self): self.chimp = MailChimp('c208efd742b3f02aa8d2f23a10d0a407-us2', debug=True) self.campaign_id = self.listCampaigns()[0]['id'] def listCampaigns(self): return self.chimp.lists() def listSubscribe(self, list_id, profile): return self.chimp.listSubscribe(id=list_id, email_address=profile.user.email, merge_vars={'FNAME': profile.username}, double_optin=False)
def register_user(sender, instance = None, created = False, **kwargs): logger.info("Registering user: %s, created: %s" % (instance.user_profile.email, created)) if created: send_welcome_email(instance) # lookup the profile for the registered user profile = instance.user_profile try: mailchimp_event = MailChimpEvent.objects.get(event = instance.event) mailchimp = MailChimp(settings.MAILCHIMP_API_KEY) event = instance.event event_start_datetime = event.start_date_timezone('America/Toronto').strftime('%A, %b %d, %I:%M %p') event_start_date = event.start_date_timezone('America/Toronto').strftime('%A, %b %d') event_start_time = event.start_date_timezone('America/Toronto').strftime('%I:%M %p') result = mailchimp.listSubscribe( id = settings.MAILCHIMP_LIST_ID, email_address = profile.email, merge_vars = { 'FNAME': profile.first_name, 'LNAME': profile.last_name, 'ADDRESS': { 'city': profile.city, 'state': profile.province, 'zip': profile.postal_code, 'country': 'Canada' }, 'EVENT_TITLE': instance.event.name, 'EVENT_DATETIME': event_start_datetime, 'EVENT_DATE': event_start_date, 'EVENT_TIME': event_start_time, 'EVENT_TAGLINE': event.short_description, 'EVENT_LONGDESC': event.description, 'EVENT_OUTLOOKLINK': "http://home.v13inc.com/%s/%s" % (settings.MEDIA_URL, event.outlook_file) }, double_optin = False, welcome_email = True, update_existing = True ) logger.info("Adding %s to list '%s', result: %s" % (profile.email, settings.MAILCHIMP_LIST_ID, result)) result = mailchimp.listStaticSegmentAddMembers( id = settings.MAILCHIMP_LIST_ID, seg_id = mailchimp_event.list_segment_id, batch = [profile.email] ) logger.info("Adding %s to list segment '%s': %s" % (profile.email, mailchimp_event.list_segment_id, result)) except MailChimpEvent.DoesNotExist: logger.info("Unable to add user to list, no MailChimpEvent for current event")
def mailing_list_signup(request): email = request.POST.get('email', '') if email_re.match(email): social = request.site.social mailchimp = MailChimp(social.mailchimp_api_key) try: response = mailchimp.listSubscribe( id=social.mailchimp_list_id, email_address=email, merge_vars='' ) except MailChimpError, e: if e.code == 214: messages.success(request, 'You are already on our mailing list. Thanks for your continued interest!') else: if response is True: success_msg = 'Thanks for signing up! We\'ll send you a confirmation e-mail shortly.' messages.success(request, success_msg) else: messages.warning(request, 'We were unable to sign you up at this time. Please try again.')
def run(): mc = MailChimp(key) list = settings.MAILCHIMP_LISTID # ---------------------------------------------------------------------- # handle unsubscribes first emails = [] unsub = ListEvent.objects.filter(subscribe=False) for u in unsub: print "unsubscribing", fix_encoding(u.user.visible_name()), u.email emails.append(u.email) u.delete() if len(emails): result = mc.listBatchUnsubscribe(id=list, emails=emails, delete_member=True, send_goodbye=False, send_notify=False) print_result(result) # ---------------------------------------------------------------------- # subscribe new people # (actually, this should never be used... since new subscriptions have # been rolled into ProfileEvents) emails = [] sub = ListEvent.objects.filter(subscribe=True) for s in sub: print "subscribing", fix_encoding( s.user.visible_name()), s.user.email entry = build_profile(s.user) entry['GROUPINGS'] = build_new_groups(s.user) emails.append(entry) s.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails, double_optin=False, update_existing=False) print_result(result) # ---------------------------------------------------------------------- # profile info updates # handle email address changes separately, since we can't batch those profile = ProfileEvent.objects.filter(email__isnull=False) for p in profile: if p.email: print "updating with new email", fix_encoding( p.user.visible_name()), p.email, p.user.email entry = build_profile(p.user) entry['GROUPINGS'] = build_new_groups(p.user) p.delete() result = mc.listSubscribe(id=list, email_address=p.email, merge_vars=entry, double_optin=False, send_welcome=False, update_existing=True, replace_interests=False) print result # and everything else profile = ProfileEvent.objects.all() for p in profile: print "updating", fix_encoding(p.user.visible_name()), p.user.email entry = build_profile(p.user) entry['GROUPINGS'] = build_new_groups(p.user) emails.append(entry) p.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails, double_optin=False, update_existing=True, replace_interests=False) print_result(result) # ---------------------------------------------------------------------- # group joins emails = {} join = GroupEvent.objects.filter(join=True) for j in join: print fix_encoding( j.user.visible_name()), j.user.email, "joining", fix_encoding( j.group.name) # if they're not already on the list, build a profile for them if not emails.has_key(j.user.id): emails[j.user.id] = build_profile(j.user) emails[j.user.id]['GROUPINGS'] = [] # add this group to the user's list of groups emails[j.user.id]['GROUPINGS'] = add_group( j.group, emails[j.user.id]['GROUPINGS']) # ok, done. j.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails.values(), double_optin=False, update_existing=True, replace_interests=False) print_result(result) # ---------------------------------------------------------------------- # group leaves emails = {} leave = GroupEvent.objects.filter(join=False) for l in leave: print fix_encoding( l.user.visible_name()), l.user.email, "leaving", fix_encoding( l.group.name) # if they're not already on the list, build a profile for them try: if l.user.id not in emails: emails[l.user.id] = build_profile(l.user) info = mc.listMemberInfo(id=list, email_address=l.user.email) emails[ l.user.id]['GROUPINGS'] = info['merges']['GROUPINGS'] # remove group from list emails[l.user.id]['GROUPINGS'] = remove_group( l.group, emails[l.user.id]['GROUPINGS']) except: print "--ERROR" # ok, done. l.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails.values(), double_optin=False, update_existing=True, replace_interests=True) print_result(result)
def run(): mc = MailChimp(key) list = settings.MAILCHIMP_LISTID # ---------------------------------------------------------------------- # handle unsubscribes first emails = [] unsub = ListEvent.objects.filter(subscribe=False) for u in unsub: print "unsubscribing", to_ascii(u.user.visible_name()), u.email emails.append(u.email) u.delete() if len(emails): result = mc.listBatchUnsubscribe(id=list, emails=emails, delete_member=True, send_goodbye=False, send_notify=False) print_result(result) # ---------------------------------------------------------------------- # subscribe new people # (actually, this should never be used... since new subscriptions have # been rolled into ProfileEvents) emails = [] sub = ListEvent.objects.filter(subscribe=True) for s in sub: print "subscribing", to_ascii(s.user.visible_name()), s.user.email entry = build_profile(s.user) entry['GROUPINGS'] = build_new_groups(s.user) emails.append(entry) s.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails, double_optin=False, update_existing=False) print_result(result) # ---------------------------------------------------------------------- # profile info updates # handle email address changes separately, since we can't batch those profile = ProfileEvent.objects.filter(email__isnull=False) for p in profile: if p.email: print "updating with new email", to_ascii(p.user.visible_name()), p.email, p.user.email entry = build_profile(p.user) entry['GROUPINGS'] = build_new_groups(p.user) p.delete() result = mc.listSubscribe(id=list, email_address=p.email, merge_vars=entry, double_optin=False, send_welcome=False, update_existing=True, replace_interests=False) print result # and everything else profile = ProfileEvent.objects.all() for p in profile: print "updating", to_ascii(p.user.visible_name()), p.user.email entry = build_profile(p.user) entry['GROUPINGS'] = build_new_groups(p.user) emails.append(entry) p.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails, double_optin=False, update_existing=True, replace_interests=False) print_result(result) # ---------------------------------------------------------------------- # group joins emails = {} join = GroupEvent.objects.filter(join=True) for j in join: print to_ascii(j.user.visible_name()), j.user.email, "joining", fix_encoding(j.group.name) # if they're not already on the list, build a profile for them if not emails.has_key(j.user.id): emails[j.user.id] = build_profile(j.user) emails[j.user.id]['GROUPINGS'] = [] # add this group to the user's list of groups emails[j.user.id]['GROUPINGS'] = add_group(j.group, emails[j.user.id]['GROUPINGS']) # ok, done. j.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails.values(), double_optin=False, update_existing=True, replace_interests=False) print_result(result) # ---------------------------------------------------------------------- # group leaves emails = {} leave = GroupEvent.objects.filter(join=False) for l in leave: print to_ascii(l.user.visible_name()), l.user.email, "leaving", fix_encoding(l.group.name) # if they're not already on the list, build a profile for them try: if l.user.id not in emails: emails[l.user.id] = build_profile(l.user) info = mc.listMemberInfo(id=list, email_address=l.user.email) emails[l.user.id]['GROUPINGS'] = info['merges']['GROUPINGS'] # remove group from list emails[l.user.id]['GROUPINGS'] = remove_group(l.group, emails[l.user.id]['GROUPINGS']) except: print "--ERROR" # ok, done. l.delete() if len(emails): result = mc.listBatchSubscribe(id=list, batch=emails.values(), double_optin=False, update_existing=True, replace_interests=True) print_result(result)