示例#1
0
  def create_campaign(self, subject_format, schedule_time = None, time_str = None, template_id = None):
    mailchimp = MailChimp(settings.MAILCHIMP_API_KEY)
    campaign_id = mailchimp.campaignCreate(
        type = 'regular',
        content = {'html_mid_content00': self.event.description},
        segment_opts = {'match': 'all', 'conditions': [{
                              'field': 'static_segment',
                              'op': 'eq',
                              'value': self.list_segment_id
                        }]},
        options = {
          'list_id': settings.MAILCHIMP_LIST_ID,
          'subject': subject_format.format(event = self.event.name, time = time_str), 
          'from_email': settings.MAILCHIMP_FROM_EMAIL,
          'from_name': settings.MAILCHIMP_FROM_NAME,
          'to_email': settings.MAILCHIMP_TO_EMAIL,
          'template_id': template_id,
        }
    )

    if schedule_time != None:
      try:
        mailchimp.campaignSchedule(cid = campaign_id, schedule_time = schedule_time)
      except MailChimpError as error:
        logger.error("Campaign scheduled in the past: %s" % error.msg)

    return campaign_id
示例#2
0
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")
示例#3
0
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()
示例#4
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, ))
示例#5
0
def mailchimp_template_choices():
  mailchimp = MailChimp(settings.MAILCHIMP_API_KEY)
  templates = mailchimp.campaignTemplates()

  choices = []
  for template in templates:
    choices.append((template['id'], template['name']))

  return choices
示例#6
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
示例#7
0
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)
示例#8
0
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)
示例#9
0
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")
示例#10
0
 def create_segment(self, name):
   segment_name = name[:25]
   mailchimp = MailChimp(settings.MAILCHIMP_API_KEY)
   try:
     segment_id = mailchimp.listAddStaticSegment(
         id = settings.MAILCHIMP_LIST_ID,
         name = segment_name
     )
   except MailChimpError as error:
     logger.error("MailChimp segment already exists: %s" % error.msg)
     # find the matching segment
     logger.info("Finding segments with name: %s" % segment_name)
     for segment in mailchimp.listStaticSegments(id = settings.MAILCHIMP_LIST_ID):
       if segment['name'] == segment_name:
         segment_id = segment['id']
         logger.info("Found matching segment for '%s': %s" % (segment_name, segment['id']))
   
   return segment_id
示例#11
0
文件: views.py 项目: tonomuniz/tiger
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.')
示例#12
0
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()
示例#13
0
  def create_event_finished_campaigns(self):
    finished_date = self.event.live_stop_date.replace(tzinfo = timezone(settings.TIME_ZONE))
    event_finished_time = self.gmt_timestamp(finished_date)

    mailchimp = MailChimp(settings.MAILCHIMP_API_KEY)
    self.campaign_sorry_id = mailchimp.campaignCreate(
        type = 'regular',
        content = {'html_mid_content00': self.event.description},
        segment_opts = {'match': 'all', 'conditions': [{
                              'field': 'static_segment',
                              'op': 'eq',
                              'value': self.participated_segment_id
                        }]},
        options = {
          'list_id': settings.MAILCHIMP_LIST_ID,
          'subject': settings.MAILCHIMP_SUBJECTS['finished_sorry_we_missed'],
          'from_email': settings.MAILCHIMP_FROM_EMAIL,
          'from_name': settings.MAILCHIMP_FROM_NAME,
          'to_email': settings.MAILCHIMP_TO_EMAIL,
          'template_id': self.event.template_missed_you,
        }
    )

    self.campaign_thanks_id = mailchimp.campaignCreate(
        type = 'regular',
        content = {'html_mid_content00': self.event.description},
        segment_opts = {'match': 'all', 'conditions': [
                            {
                              'field': 'static_segment',
                              'op': 'ne',
                              'value': self.participated_segment_id
                            },
                            {
                              'field': 'static_segment',
                              'op': 'eq',
                              'value': self.list_segment_id
                            }]},
        options = {
          'list_id': settings.MAILCHIMP_LIST_ID,
          'subject': settings.MAILCHIMP_SUBJECTS['finished_thank_you'],
          'from_email': settings.MAILCHIMP_FROM_EMAIL,
          'from_name': settings.MAILCHIMP_FROM_NAME,
          'to_email': settings.MAILCHIMP_TO_EMAIL,
          'template_id': self.event.template_thank_you,
        }
    )
    try:
      mailchimp.campaignSchedule(cid = self.campaign_thanks_id, schedule_time = event_finished_time)
      mailchimp.campaignSchedule(cid = self.campaign_sorry_id, schedule_time = event_finished_time)
    except MailChimpError as error:
      logger.error("Campaign scheduled in the past: %s" % error.msg)
示例#14
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)
         )
示例#15
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()
示例#16
0
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()
示例#17
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)
示例#18
0
 def __init__(self):
     self.chimp = MailChimp('c208efd742b3f02aa8d2f23a10d0a407-us2',
                            debug=True)
     self.campaign_id = self.listCampaigns()[0]['id']
示例#19
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", 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)
示例#20
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'
示例#21
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)
示例#22
0
 def __init__(self):
     self.chimp = MailChimp('c208efd742b3f02aa8d2f23a10d0a407-us2', debug=True)
     self.campaign_id = self.listCampaigns()[0]['id']
示例#23
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'