Example #1
0
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, ))
Example #2
0
 def mailchimp_lists(self):
     CACHE_KEY = Social.MAILCHIMP_CACHE_KEY % self.id
     mailchimp_choices = cache.get(CACHE_KEY)
     if mailchimp_choices is None:
         mailchimp = MailChimp(self.mailchimp_api_key)
         mailchimp_choices = [
             (lst['id'], lst['name'])
             for lst in mailchimp.lists()
         ]
         cache.set(CACHE_KEY, mailchimp_choices, 3600)
     return mailchimp_choices
Example #3
0
def _makeusers():
    """
    Helper function to create user accounts. Meant for one-time use 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:
                addmailchimp(mc, p)
    db.session.commit()
Example #4
0
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.')
Example #5
0
 def dispatch_mailchimp(self):
     site = self.site
     social = site.social
     if social.mailchimp_send_blast != Social.CAMPAIGN_NO_CREATE:
         mailchimp = MailChimp(social.mailchimp_api_key)
         campaign_id = mailchimp.campaignCreate(
             type='regular',
             options={
                 'list_id': social.mailchimp_list_id,
                 'subject': self.title,
                 'from_email': social.mailchimp_from_email,
                 'from_name': site.name,
                 'to_name': '%s subscribers' % site.name,
             },
             content={
                 'html': self.get_body_html(),
                 'text': self.get_body_text()
         })
         if social.mailchimp_send_blast == Social.CAMPAIGN_SEND:
             mailchimp.campaignSendNow(cid=campaign_id)
         data_center = social.mailchimp_api_key.split('-')[1]
         Release.objects.filter(id=self.id).update(
             mailchimp = 'http://%s.admin.mailchimp.com/campaigns/show?id=%s' % (data_center, campaign_id)
         )
Example #6
0
    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)
Example #7
0
 def __init__(self):
     self.chimp = MailChimp('c208efd742b3f02aa8d2f23a10d0a407-us2',
                            debug=True)
     self.campaign_id = self.listCampaigns()[0]['id']
Example #8
0
def admin_venue(edition):
    if request.method == 'GET' and 'email' not in request.args:
        return render_template('venuereg.html', edition=edition)
    elif request.method == 'POST' or 'email' in request.args:
        if 'email' in request.args:
            formid = 'venueregemail'
        else:
            formid = request.form.get('form.id')
        if formid == 'venueregemail':
            email = request.values.get('email')
            if email:
                p = Participant.query.filter_by(edition=edition,
                                                email=email).first()
                if p is not None:
                    if p.attended:  # Already signed in
                        flash(
                            "You have already signed in. Next person please.")
                        return redirect(url_for('admin_venue',
                                                edition=edition),
                                        code=303)
                    else:
                        return render_template('venueregdetails.html',
                                               edition=edition,
                                               p=p)
            # Unknown email address. Ask for new registration
            regform = RegisterForm()
            regform.email.data = email
            regform.edition.data = edition
            return render_template('venueregnew.html',
                                   edition=edition,
                                   regform=regform)
        elif formid == 'venueregconfirm':
            id = request.form['id']
            subscribe = request.form.get('subscribe')
            p = Participant.query.get(id)
            if subscribe:
                p.subscribe = True
            else:
                p.subscribe = False
            p.attended = True
            p.attenddate = datetime.utcnow()
            db.session.commit()
            flash("You have been signed in. Next person please.", 'info')
            return redirect(url_for('admin_venue', edition=edition), code=303)
        elif formid == 'venueregform':
            # Validate form and register
            regform = RegisterForm()
            regform._venuereg = edition
            if regform.validate_on_submit():
                participant = Participant()
                regform.populate_obj(participant)
                participant.ipaddr = request.environ['REMOTE_ADDR']
                # Do not record participant.useragent since it's a venue computer, not user's.
                makeuser(participant)
                db.session.add(participant)
                if MailChimp is not None and app.config[
                        'MAILCHIMP_API_KEY'] and app.config[
                            'MAILCHIMP_LIST_ID']:
                    mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
                    addmailchimp(mc, participant)
                db.session.commit()
                return render_template('venueregsuccess.html',
                                       edition=edition,
                                       p=participant)
            else:
                return render_template('venueregform.html',
                                       edition=edition,
                                       regform=regform,
                                       ajax_re_register=True)
        else:
            flash("Unknown form submission", 'error')
            return redirect(url_for('admin_venue', edition=edition), code=303)
Example #9
0
def admin_approve(edition):
    if request.method == 'GET':
        tz = timezone(app.config['TIMEZONE'])
        return render_template(
            'approve.html',
            participants=Participant.query.filter_by(edition=edition),
            utc=utc,
            tz=tz,
            enumerate=enumerate,
            edition=edition)
    elif request.method == 'POST':
        p = Participant.query.get(request.form['id'])
        if not p:
            status = "No such user"
        else:
            if 'action.undo' in request.form:
                p.approved = False
                p.user = None
                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:
                if p.approved:
                    status = "Already approved"
                else:
                    # Check for dupe participant (same email, same edition)
                    dupe = False
                    for other in Participant.query.filter_by(edition=p.edition,
                                                             email=p.email):
                        if other.id != p.id:
                            if other.user:
                                dupe = True
                                break
                    if dupe == False:
                        p.approved = True
                        status = "Tada!"
                        # 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'])
                            addmailchimp(mc, p)
                        # 3. Send notice of approval
                        msg = Message(
                            subject="Your registration has been approved",
                            recipients=[p.email])
                        msg.body = render_template("approve_notice_%s.md" %
                                                   edition,
                                                   p=p)
                        msg.html = markdown(msg.body)
                        with app.open_resource("static/doctypehtml5-%s.ics" %
                                               edition) as ics:
                            msg.attach("doctypehtml5.ics", "text/calendar",
                                       ics.read())
                        mail.send(msg)
                        db.session.commit()
                    else:
                        status = "Dupe"
            else:
                status = 'Unknown action'