def submit(request): # grab info email = request.POST['email'] referrer = request.POST['referrer'] # save locally lead_to_submit = Lead(email=email, referrer=referrer) lead_to_submit.save() # send to Mailchimp key = settings.MAILCHIMP_API_KEY list_num = settings.MAILCHIMP_LIST_NUM # see: http://www.nerdydork.com/integrate-mailchimp-with-your-django-app.html mailsnake = MailSnake(key) try: mailsnake.listSubscribe( id=list_num, email_address=email, double_optin=False, send_welcome=False, merge_vars={ 'referrer': referrer } ) except: pass return HttpResponseRedirect(reverse('landingpage.views.thanks'))
def add_customer_to_mailing_list(customer): ''' When called, this adds the customer's email to the mailing list. ''' if not hasattr(settings, 'MAILCHIMP_API_KEY') or not hasattr( settings, 'MAILCHIMP_LIST_ID'): logger.info( 'Did not update mailing list to add customer %s, MailChimp is not set up.' % customer.id) return logger.info('Updating mailing list in MailChimp, adding customer %s.' % customer.id) ms = MailSnake(settings.MAILCHIMP_API_KEY) listId = settings.MAILCHIMP_LIST_ID ms.listSubscribe(id=listId, email_address=customer.email, email_type='html', double_optin=False, update_existing=True, merge_vars={ 'FNAME': customer.first_name, 'LNAME': customer.last_name })
def update_main_list_segment(self): segment_name = 'Ticketholders' segment_id = None tix = Ticket.query.filter_by(paid=True).join(User).\ group_by(User).with_entities(User).order_by(User.id) email_addresses = [ticket.email for ticket in tix] ms = MailSnake(app.config['MAILCHIMP_KEY']) segments = ms.listStaticSegments(id=app.config['MAILCHIMP_LIST']) for segment in segments: if segment['name'] == segment_name: segment_id = segment['id'] if segment_id is None: segment_id = ms.listStaticSegmentAdd( id=app.config['MAILCHIMP_LIST'], name=segment_name) results = ms.listStaticSegmentMembersAdd( id=app.config['MAILCHIMP_LIST'], seg_id=segment_id, batch=email_addresses) app.logger.info("Segment updated. Success: %s, failed: %s", results['success'], len(results['errors']))
def main(mailchimp_key, list_id, rapleaf_key): thirty_days_ago = datetime.datetime.now() - datetime.timedelta(days=30) ms = MailSnake(mailchimp_key) rapleaf = RapleafApi.RapleafApi(rapleaf_key) members = ms.listMembers(id=list_id, limit=1500)['data'] active_members = [] for member in members: member_activity = ms.listMemberActivity(id=list_id, email_address=member['email']) actions = [action for action in member_activity['data'][0] if action['action'] == 'open'] if actions: last_action = actions[0] last_event = datetime.datetime.strptime(last_action['timestamp'], "%Y-%m-%d %H:%M:%S") if last_event > thirty_days_ago: active_members.append(member['email']) age_map = defaultdict(int) for active_member in active_members: try: response = rapleaf.query_by_email(active_member) age = response.get("age") age_map[age] += 1 # for k, v in response.iteritems(): # print '%s = %s' % (k, v) except Exception as e: print e for x, y in age_map.iteritems(): print x, y
def update_ticketholders_list(self): ms = MailSnake(app.config['MAILCHIMP_KEY']) list_id = '5f939ca32a' # Ticketholders 2016 tix = Ticket.query.filter_by(paid=True).join(User).\ group_by(User).with_entities(User).order_by(User.id) list_members = { member['email'] for member in ms.listMembers(id=list_id, limit=10000)['data'] } current_users = {ticket.email for ticket in tix} to_remove = list_members - current_users to_add = current_users - list_members app.logger.info( "Ticketholders list: adding %s addresses, removing %s addresses", len(to_add), len(to_remove)) res = ms.listBatchUnsubscribe(id=list_id, emails=list(to_remove), send_goodbye=False) print(res) to_add_data = [{ 'EMAIL': email, 'EMAIL_TYPE': 'html' } for email in to_add] res = ms.listBatchSubscribe(id=list_id, batch=to_add_data, double_optin=False, update_existing=True) print(res)
def earlyAccessSubmit(request): from signup.forms import SignupForm if request.method == 'POST': # If the form has been submitted... form = SignupForm(request.POST) # A form bound to the POST data if form.is_valid(): ms = MailSnake('60a810702ef83b7de50b150df5008109-us5') lists = ms.lists() ms.listSubscribe( id=lists['data'][0]['id'], email_address=form.cleaned_data['email'], merge_vars={ 'GROUPINGS': [ { 'id': 7197, 'groups': 'Pre-Launch', }, ] }, update_existing=True, double_optin=False, ) return HttpResponseRedirect( '/signup/thanks/') # Redirect after POST else: form = SignupForm() # An unbound form return render(request, 'signup.html', { 'form': form, })
def test_pending_user_subscription(self): ms = MailSnake(settings.MAILCHIMP_API_KEY) user = get_admin_user() subscription = UserSubscription.objects.get(user=user) delete_member(user) ms.listInterestGroupingAdd(id=get_list_id(), name="Test Interest Group", type="checkboxes", groups=["Option 1", "Option 2"]) # when a user signs up... pending, c = PendingUserSubscription.objects.get_or_create(user=user) optin_ip = getattr(settings, 'MAILCHIMP_TEST_IP', '184.106.168.48') optin_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') pending.merge_vars = { 'OPTIN_IP': optin_ip, 'OPTIN_TIME': optin_time, } pending.save() # when the user is activated, confirmed, etc. pending.subscribe(double_optin=False) subscription.sync() self.assertEqual(optin_ip, subscription.optin_ip) self.assertEqual(optin_time, subscription.optin_time) self.assertTrue(subscription.is_subscribed()) pending.delete()
def submit(request): # grab info email = request.POST['email'] referrer = request.POST['referrer'] # save locally # lead_to_submit = Lead(email=email, referrer=referrer) # lead_to_submit.save() # send to Mailchimp key = settings.MAILCHIMP_API_KEY list_num = settings.MAILCHIMP_LIST_NUM # see: http://www.nerdydork.com/integrate-mailchimp-with-your-django-app.html mailsnake = MailSnake(key) try: mailsnake.listSubscribe(id=list_num, email_address=email, double_optin=False, send_welcome=False, merge_vars={'referrer': referrer}) except: pass return HttpResponseRedirect(reverse('landingpage.views.thanks'))
def edit_profile(request): user = request.user email = user.email #after submission if request.method == 'POST': edit_profile_form = EditProfileForm(request.POST, request.FILES, instance=user.profile) edit_user_form = EditUserForm(request.POST, request.FILES, instance=user, request=request) #success if edit_profile_form.is_valid() and edit_user_form.is_valid(): ms = MailSnake('f92abfa01e0a9cecc885186de4e37106-us7') print user.email ms.listUpdateMember(id='ed61191f4e', email_address=email, merge_vars={ 'FNAME':edit_user_form.cleaned_data.get('first_name'), 'LNAME':edit_user_form.cleaned_data.get('last_name'), 'EMAIL':edit_user_form.cleaned_data.get('email'), }) edit_profile_form.save() edit_user_form.save() return redirect('/profiles/' + user.username) #before submission else: edit_profile_form = EditProfileForm(instance=user.profile) edit_user_form = EditUserForm(instance=user, request=request) user_profile = user return render(request, 'edit_profile.html', {'edit_profile_form': edit_profile_form, 'edit_user_form': edit_user_form, 'user_profile' : user_profile })
def update_user_details(backend, details, uid, response, user=None, is_new=False, *args, **kwargs): if user is None: return changed = False # flag to track changes for name, value in details.iteritems(): # configured fields if user already existed if not _ignore_field(name, is_new): if value and value != getattr(user, name, None): setattr(user, name, value) changed = True user.profile.activate() user.profile.fb_pic(uid) user.save() #add to mailchimp list if user.first_name: try: ms = MailSnake('f92abfa01e0a9cecc885186de4e37106-us7') key = '' ms.listSubscribe( id = 'ed61191f4e', email_address = user.email, merge_vars = { 'FNAME': user.first_name, 'LNAME': user.last_name, 'EKEY': key }, double_optin = False, send_welcome = False ) except: print "Facebook login error: Couldn't add user to MailChimp list" else: user.profile.send_welcome_email(activate=False)
def earlyAccessSubmit(request): from signup.forms import SignupForm if request.method == 'POST': # If the form has been submitted... form = SignupForm(request.POST) # A form bound to the POST data if form.is_valid(): ms = MailSnake('60a810702ef83b7de50b150df5008109-us5') lists = ms.lists() ms.listSubscribe( id = lists['data'][0]['id'], email_address = form.cleaned_data['email'], merge_vars = { 'GROUPINGS': [ {'id': 7197, 'groups': 'Pre-Launch',},] }, update_existing = True, double_optin = False, ) return HttpResponseRedirect('/signup/thanks/') # Redirect after POST else: form = SignupForm() # An unbound form return render(request, 'signup.html', { 'form': form, })
def main_post(): ms = MailSnake(app.config['MAILCHIMP_KEY']) try: email = request.form.get('email') ms.listSubscribe(id=app.config['MAILCHIMP_LIST'], email_address=email) flash('Thanks for subscribing! You will receive a confirmation email shortly.') except InvalidEmailException as e: app.logger.info('Invalid email address: %r', email) flash("Your email address was not accepted - please check and try again.") except ListAlreadySubscribedException as e: app.logger.info('Already subscribed: %s', email) if e.message: msg = Markup(e.message) else: msg = """You are already subscribed to our list. Please contact %s to update your settings.""" % app.config['TICKETS_EMAIL'][1] flash(msg) except MailSnakeException as e: app.logger.error('Error subscribing: %r', e) flash('Sorry, an error occurred.') return redirect(url_for('.main'))
def main_post(): ms = MailSnake(app.config['MAILCHIMP_KEY']) try: email = request.form.get('email') ms.listSubscribe(id=app.config['MAILCHIMP_LIST'], email_address=email) flash( 'Thanks for subscribing! You will receive a confirmation email shortly.' ) except InvalidEmailException as e: app.logger.info('Invalid email address: %r', email) flash( "Your email address was not accepted - please check and try again." ) except ListAlreadySubscribedException as e: app.logger.info('Already subscribed: %s', email) if e.message: msg = Markup(e.message) else: msg = """You are already subscribed to our list. Please contact %s to update your settings.""" % app.config[ 'TICKETS_EMAIL'][1] flash(msg) except MailSnakeException as e: app.logger.error('Error subscribing: %r', e) flash('Sorry, an error occurred.') return redirect(url_for('.main'))
def api_createuser(request): code = 100 data = {'code':code, 'error': 'Request Error'} if request.POST: if 'name' in request.POST and 'email' in request.POST and 'password' in request.POST: name = request.POST['name'] email_x = request.POST['email'] password = request.POST['password'] email = email_x.lower() if validateEmail(email): ck_u = User.objects.filter(email=email) if len(ck_u) > 0: existing_user = True code = 100 data = {'code':code, 'error': 'User Already Exists'} else: existing_user = False u = User(username=email, password=password, email=email) u.save() """create invitation""" store = Store.objects.filter(active=True,city='San Francisco')[0] inv = Invitation(user=u, default_store=store, email=u.username, used=True) inv.save() up = UserProfile(user=u, default_store=store) up.save() """create default subscription""" sub = Subscription(userprofile=up, subscription=False, subscription_type='un-subscribed') sub.save() """Send admin email""" sendSignupAdminEmail(u, 'San Francisco') """Send user email""" sendWelcomeEmail(email,'sanfrancisco', 'San Francisco') """subscribe user to daily email""" LIST_IDS = {'san-francisco':'eaa0a378ba'} l_id = LIST_IDS['san-francisco'] ms = MailSnake(settings.MAILCHIMP_API_KEY) success = ms.listSubscribe(id=l_id, email_address=u.email, double_optin=False) d, code = api_auth_helper(u) code = 200 data = {'code':code, 'account':d['account']} else: code = 100 data = {'code':code, 'error': 'Invalid Email'} else: code = 100 data = {'code':code, 'error': 'Invalid Sign-up'} return HttpResponse(simplejson.dumps(data, cls=MyJSONEncoder),content_type = 'application/javascript; charset=utf8')
def find_list(name): mc = MailSnake(settings.MC_API_KEY) lists = mc.lists(filters={"list_name": name}) if lists["total"] == 0: return 0 return lists["data"][0]["id"]
def find_list(name): mc = MailSnake(settings.MC_API_KEY) lists = mc.lists(filters={"list_name": name}) if lists['total'] == 0: return 0 return lists['data'][0]['id']
def find_list(name): mc = MailSnake(settings.MC_API_KEY) lists = mc.lists(filters = {"list_name": name}) if lists['total'] == 0: return 0 return lists['data'][0]['id']
def __init__(self, active=True): self.__active = active if self.__active: from mailsnake import MailSnake self.ms = MailSnake(conf.MAILCHIMP_APIKEY) self.lists = {} for name, list_id in chain(os_lists.items(), general_lists.items()): self.add_list(name=name, list_id=list_id)
def find_template(name): mc = MailSnake(settings.MC_API_KEY) templates = mc.templates()['user'] for temp in templates: if temp['name'] == name: return temp['id'] return 0
def connect_mailchimp(api_key): """ Initializes connection to the mailchimp api """ mailchimp = MailSnake(api_key) result = mailchimp.ping() log.debug(result) return mailchimp
def main_post(): ms = MailSnake(app.config["MAILCHIMP_KEY"]) try: email = request.form.get("email") ms.listSubscribe(id="d1798f7c80", email_address=email) flash("Thanks for subscribing! You will receive a confirmation email shortly.") except MailSnakeException, e: print e flash("Sorry, an error occurred.")
def main_post(): ms = MailSnake(app.config['MAILCHIMP_KEY']) try: email = request.form.get('email') ms.listSubscribe(id='d1798f7c80', email_address=email) flash('Thanks for subscribing! You will receive a confirmation email shortly.') except MailSnakeException, e: print e flash('Sorry, an error occurred.')
def find_template(name): mc = MailSnake(settings.MC_API_KEY) templates = mc.templates()["user"] for temp in templates: if temp["name"] == name: return temp["id"] return 0
def main_post(): ms = MailSnake(app.config['MAILCHIMP_KEY']) try: email = request.form.get('email') ms.listSubscribe(id='d1798f7c80', email_address=email) flash('Thanks for subscribing! You will receive a confirmation email shortly.') except MailSnakeException, e: app.logger.error('Error subscribing: %s', e) flash('Sorry, an error occurred.')
def form_valid(self, form): ms = MailSnake(getattr(settings, 'MAILCHIMP_KEY')) double_optin = getattr(settings, 'MAILCHIMP_CONFIRM', True) list_id = getattr(settings, 'MAILCHIMP_LIST_ID', None) if not list_id: list_id = ms.lists()['data'][0]['id'] ms.listSubscribe(id=list_id, email_address=form.cleaned_data['email'], merge_vars={'NAME': form.cleaned_data['name']}, update_existing=True, double_optin=double_optin) return super(SubscribeView, self).form_valid(form)
def __add_to_mailchimp(user): if settings.MAILCHIMP_AUTO_SUBSCRIBE: ms = MailSnake(settings.MAILCHIMP_API_KEY) ms.listSubscribe( id=settings.MAILCHIMP_LIST_ID, email_address=user.email, merge_vars={ 'FNAME': user.first_name, 'LNAME': user.last_name, }, double_optin=False, # no confirm message send_welcome=True, # if new, send welcome update_existing=True, # if existing, update )
def __init__(self, config, state): self.config = config self.state = state apikey = config['access_token'] + '-' + config['dc'] self.mailsnake = MailSnake(apikey) self.client = Client(config, self) self.export_client = MailSnake(apikey, api='export', requests_opts={'stream': True}) self._catalog = None self.campaigns = [] self.lists = [] self.selected_stream_ids = None self.now = datetime.utcnow()
def newsletter_signup(request): email = request.POST['email'] if re.match('^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$', email): ms = MailSnake(settings.MAILCHIMP_KEY) r = ms.listSubscribe(id='df179acee6', email_address=email) print(r) if r: return HttpResponse() else: return HttpResponseServerError() else: #Invalid email address. Return 400 return HttpResponseBadRequest(content='Invalid email address')
class MailChimp(object): def __init__(self, apikey): self.api_key = apikey self.provider = MailSnake(self.api_key) def test_connection(self): try: self.provider.ping() except Exception, err: logging.error(err) return False return True
def create_campaign(html, text): mc = MailSnake(settings.MC_API_KEY) options = { "subject": datetime.today().strftime(settings.SUBJECT_TEMPLATE), "from_email": settings.MC_EMAIL, "from_name": settings.MC_FROM_NAME, "to_name": settings.MC_TO_NAME, "template_id": find_template(settings.MC_TEMPLATE_NAME), "list_id": find_list(settings.MC_LIST_NAME), } section_name = "html_" + settings.MC_TEMPLATE_SECTION content = {section_name: html, "text": text} cid = mc.campaignCreate(type="regular", content=content, options=options) return cid
def campaign_info(cid): mc = MailSnake(settings.MC_API_KEY) campaigns = mc.campaigns(filters={"campaign_id": cid}) if campaigns["total"] == 0: return 0 webid = campaigns["data"][0]["web_id"] title = campaigns["data"][0]["title"] region = settings.MC_API_KEY.split("-")[1] url = "https://%s.admin.mailchimp.com/campaigns/show?id=%d" % (region, webid) return title, url
def create_campaign(html, text): mc = MailSnake(settings.MC_API_KEY) options = { 'subject' : datetime.today().strftime(settings.SUBJECT_TEMPLATE), 'from_email' : settings.MC_EMAIL, 'from_name' : settings.MC_FROM_NAME, 'to_name' : settings.MC_TO_NAME, 'template_id' : find_template(settings.MC_TEMPLATE_NAME), 'list_id' : find_list(settings.MC_LIST_NAME) } section_name = 'html_' + settings.MC_TEMPLATE_SECTION content = {section_name: html, "text": text} cid = mc.campaignCreate(type='regular', content=content, options=options) return cid
def campaign_info(cid): mc = MailSnake(settings.MC_API_KEY) campaigns = mc.campaigns(filters = {"campaign_id": cid}) if campaigns['total'] == 0: return 0 webid = campaigns['data'][0]['web_id'] title = campaigns['data'][0]['title'] region = settings.MC_API_KEY.split('-')[1] url = "https://%s.admin.mailchimp.com/campaigns/show?id=%d" % (region, webid) return title, url
def create_campaign(html, text): mc = MailSnake(settings.MC_API_KEY) options = { "subject": datetime.today().strftime(settings.SUBJECT_TEMPLATE), "from_email": settings.MC_EMAIL, "from_name": settings.MC_FROM_NAME, "to_name": settings.MC_TO_NAME, "template_id": find_template(settings.MC_TEMPLATE_NAME), "list_id": find_list(settings.MC_LIST_NAME) } section_name = 'html_' + settings.MC_TEMPLATE_SECTION content = {section_name: html, "text": text} cid = mc.campaignCreate(type='regular', content=content, options=options) return cid
def connect(request): ms = MailSnake(settings.MAILCHIMP_API_KEY) lists = ms.lists() if request.method == 'POST': form = ConnectForm(request.POST) message = 'the sky is falling' if form.is_valid(): ms.listSubscribe( id = lists['data'][0]['id'], email_address = (form.cleaned_data['email_signup']), update_existing = True, double_optin = False, ) #ms.listStaticSegmentMembersAdd( # id = lists['data'][0]['id'], # seg_id = 157, #Fake Development People... kill this in production! # batch = { # 'email_address': form.cleaned_data['email_signup'] # }, #) if request.is_ajax(): #success with js message = 'success!' status = True return HttpResponse(json.dumps({'message':message, 'status':status}), 'application/json') else: #success with no js return redirect('success') else: if request.is_ajax(): #error with js message = 'Invalid email address' status = False return HttpResponse(json.dumps({'message':message, 'status':status}), 'application/json') else: # error with no js form.addError('Invalid email address') else: form = ConnectForm() return render_to_response( 'signups/connect.html', { 'form': form, }, context_instance=RequestContext(request) )
def campaign_info(cid): mc = MailSnake(settings.MC_API_KEY) campaigns = mc.campaigns(filters={"campaign_id": cid}) if campaigns['total'] == 0: return 0 webid = campaigns['data'][0]['web_id'] title = campaigns['data'][0]['title'] region = settings.MC_API_KEY.split('-')[1] url = "https://%s.admin.mailchimp.com/campaigns/show?id=%d" % (region, webid) return title, url
def newsletter_signup_form(context): """ Renders a default nessletter signup form based on MailChimp. """ settings = value_or_none('settings', context) if not settings: raise ValueError("Expected 'settings' in template context.") if not settings.mailchimp_api or not settings.mailchimp_list_id: return '' request = value_or_none('request', context) if not request: raise ValueError("Expected 'request' in template context.") if request.method == 'POST': form = MailChimpSubscriptionForm(request.POST) else: form = MailChimpSubscriptionForm() msg = None msg_type = None if request.method == 'POST' and form.is_valid(): d = form.cleaned_data merge_vars = {'FNAME': d.get('mailchimp_subscription__name', '')} ms = MailSnake(settings.mailchimp_api) try: ms.listSubscribe(id=settings.mailchimp_list_id, email_address=d['mailchimp_subscription__email'], merge_vars=merge_vars) msg = 'Almost finished...We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you.' msg_type = 'success' except: msg = 'Unfortunately we were unable to process your request. Please try again later...' msg_type = 'error' # render form t = get_template('cubane/cms/newsletter_form.html') c = copy.copy(context) c['form'] = form c['msg'] = msg c['msg_type'] = msg_type return t.render(c)
def ajax_signup(request): if request.POST: new_signup = MyUserCreationForm(request.POST) if new_signup.is_valid(): new_signup.save() uname = new_signup.cleaned_data["username"] """set up so username and email are the same""" user = User.objects.get(username=uname) user.email = uname user.save() """create user profile""" store_id = request.POST.get("default_store") store = Store.objects.get(id=store_id) up = UserProfile(user=user, default_store=store) up.save() """create default subscription""" sub = Subscription(userprofile=up, subscription=False, subscription_type="un-subscribed") sub.save() """email admin of new signup""" sendSignupAdminEmail(user, store) """email user with signup information""" sendSignupEmail(user, store) """subscrbe user to daily email""" LIST_IDS = {"sflaunch_group": "eaa0a378ba"} l_id = LIST_IDS["sflaunch_group"] ms = MailSnake(settings.MAILCHIMP_API_KEY) success = ms.listSubscribe(id=l_id, email_address=user.email, double_optin=False) username = user.username password = user.password user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponse("success", status=200) return HttpResponse("Username is already taken", status=403)
class MailchimpRegistrar(object): _mail_snake = None def __init__(self): if not hasattr(settings, 'MAILCHIMP_API_KEY'): logger.error('MailChimp API key not present') self._mail_snake = MailSnake(settings.MAILCHIMP_API_KEY) def _register_email(self, email, list_id): self._mail_snake.listSubscribe(id=list_id, email_address=email, merge_vars={'EMAIL': email}, double_optin=True, update_existing=True) def subscribe_to_events_notification(self, email): list_id = settings.MAILCHIMP_EVENTS_NOTIFICATION_LIST_ID self._register_email(email, list_id)
def pre_save_user(sender, instance, **kwargs): try: original = User.objects.get(pk=instance.pk) except User.DoesNotExist: pass else: # Sync with MailChimp whenever a user becomes active if not original.is_active == instance.is_active and instance.is_active: user = instance profile = user.get_profile() mailsnake = MailSnake(settings.MAILCHIMP_API_KEY) if profile.newsletter: email = user.email.encode('utf-8') logger.debug('Subscribing ' + email + ' to MailChimp list...') try: mailsnake.listSubscribe(id=settings.MAILCHIMP_LIST_ID, email_address=email, double_optin=False, update_existing=True, send_welcome=True) except: logger.exception('Failed to subscribe ' + email + ' to MailChimp list') else: email = user.email.encode('utf-8') # If the user is already subscribed on MailChimp, go ahead and update our local state to match logger.debug('Retrieving subscription state for ' + email + ' on MailChimp list...') try: info = mailsnake.listMemberInfo( id=settings.MAILCHIMP_LIST_ID, email_address=(email, )) except: logger.exception( 'Failed to retrieve subscription state for ' + email) else: if info['success'] == 1 and info['data'][0][ 'status'] == 'subscribed': profile.newsletter = True profile.save(dispatch_signal=False)
def CreateNewUserHelper(request, c_email, c_city): email = c_email.lower() token = get_rand_token() ck_u = User.objects.filter(email=email) if len(ck_u) > 0: existing_user = True else: existing_user = False u = User(username=email, password=token, email=email) u.save() """create invitation""" store = Store.objects.filter(active=True, city="San Francisco")[0] inv = Invitation(user=u, default_store=store, email=u.username, token=token, used=False) inv.save() # save in session request.session["user"] = base64.b16encode(str(u.id)) CITY_LIST = {"san-francisco": "San Francisco"} cl_city = CITY_LIST[c_city] up = UserProfile(user=u, default_store=store) up.save() """create default subscription""" sub = Subscription(userprofile=up, subscription=False, subscription_type="un-subscribed") sub.save() """Send admin email""" sendSignupAdminEmail(u, cl_city) """Send welcome email to new user""" c = cl_city.lower() city = c.replace(" ", "") sendWelcomeEmail(email, token, city, cl_city) """subscribe user to daily email""" LIST_IDS = {"san-francisco": "eaa0a378ba"} l_id = LIST_IDS[c_city] ms = MailSnake(settings.MAILCHIMP_API_KEY) success = ms.listSubscribe(id=l_id, email_address=u.email, double_optin=False)
def handle(self, *args, **options): """ Validates that the id passed in exists in mailchimp. """ key, web_id = self.parse_options(options) mailchimp = MailSnake(key) lists = mailchimp.lists()['data'] by_web_id = {l['web_id']: l for l in lists} list_with_id = by_web_id.get(web_id, None) if list_with_id: print "id: {} for web_id: {}".format(list_with_id['id'], web_id) print "list name: {}".format(list_with_id['name']) else: print "list with web_id: {} not found.".format(web_id) sys.exit(1)
def main(): mailsnake = MailSnake("385108a2f086d0ede1a046291c92fc4f-us2") list_num = "e2f95e9547" for email in emails: try: returned = mailsnake.listUpdateMember( id=list_num, email_address=email, merge_vars={ 'PURCHASED': True } ) print "updated", email except EmailNotExistsException: print email, "isn't a subscriber" continue except ListNotSubscribedException: print email, "isn't a part of this list" continue
def admin_invite(request): if request.POST: form = InvitationForm(request.POST) if form.is_valid(): c_email = form.cleaned_data["email"] email = c_email.lower() token = get_rand_token() u = User(username=email, password=token, email=email) u.save() store = form.cleaned_data["store"] up = UserProfile(user=u, default_store=store) up.save() """create default subscription""" sub = Subscription(userprofile=up, subscription=False, subscription_type="un-subscribed") sub.save() c = store.city.lower() city = c.replace(" ", "") send_invite_email(email, token, city, store) inv = Invitation(user=u, default_store=store, email=u.username, token=token, used=False) inv.save() """subscrbe user to daily email""" LIST_IDS = {"sflaunch_group": "eaa0a378ba"} l_id = LIST_IDS["sflaunch_group"] ms = MailSnake(settings.MAILCHIMP_API_KEY) success = ms.listSubscribe(id=l_id, email_address=u.email, double_optin=False) else: form = InvitationForm() invites = Invitation.objects.all() template = "profile/admin/admin_invite.html" data = {"form": form, "invites": invites} return render_to_response(template, data, context_instance=RequestContext(request))
def account_details(self, request): if request.method == 'POST': form = ChangeDetailsForm(request.POST) else: form = ChangeDetailsForm() form.configure(request) if form.is_valid(): data = form.cleaned_data u = request.user p = get_customer_model().objects.get(user=u) if request.settings.mailchimp_enabled: # subscription details ms = MailSnake(request.settings.mailchimp_api) person_name = [data.get('first_name'), data.get('last_name')] merge_vars = {'FNAME': ' '.join(person_name)} # unsubscribe if email changed or we no longer want to be subscribed if 'email_address' in form.changed_data or ('newsletter' in form.changed_data and not data.get('newsletter')): try: ms.listUnsubscribe(id=request.settings.mailchimp_list_id, email_address=u.email) except: pass # subscribe if newsletter subscription changed or email was changed if ('email_address' in form.changed_data or 'newsletter' in form.changed_data) and data.get('newsletter'): try: ms.listSubscribe(id=request.settings.mailchimp_list_id, email_address=data.get('email_address'), merge_vars=merge_vars) except: pass # update newletter state in profile p.newsletter = data.get('newsletter') # update personal details on user record u.first_name = data.get('first_name') u.last_name = data.get('last_name') u.email = data.get('email_address') u.save() # update personal details on profile record p.title = data.get('title') p.first_name = data.get('first_name') p.last_name = data.get('last_name') p.telephone = data.get('phone') p.email = data.get('email_address') p.save() # success message and redirect to dashboard messages.success(request, 'Your details have been changed.') return HttpResponseRedirect(reverse('shop.account.index')) return { 'account_section': True, 'form': form }
def send_email_mandrill(subject, html_content, from_email, from_name, email_to, name_to): from mailsnake import MailSnake from django.conf import settings 'Send email using mandrill.com API' mapi = MailSnake(settings.MANDRILL_KEY, api='mandrill') message = { 'subject': subject, 'text': html2text.html2text(html_content), 'html': html_content, 'from_email': from_email, 'from_name': from_name, 'to': [{ 'email': email_to, 'name': name_to, }] } mapi.messages.send(message=message) return True
def pre_save_user_profile(sender, instance, raw, **kwargs): # Don't update MailChimp if this is a raw save (to prevent cycles when updating in response to the MailChimp webhook) if not raw: try: original = UserProfile.objects.get(pk=instance.pk) except UserProfile.DoesNotExist: pass else: if not original.newsletter == instance.newsletter: user = instance.user # Update MailChimp whenever the newsletter preference changes for an active user if user.is_active: email = user.email.encode('utf-8') profile = instance mailsnake = MailSnake(settings.MAILCHIMP_API_KEY) if profile.newsletter: logger.debug('Subscribing ' + email + ' to MailChimp list...') try: mailsnake.listSubscribe( id=settings.MAILCHIMP_LIST_ID, email_address=email, double_optin=False, update_existing=True, send_welcome=True) except: logger.exception('Failed to subscribe ' + email + ' to MailChimp list') else: logger.debug('Unsubscribing ' + email + ' from MailChimp list...') try: mailsnake.listUnsubscribe( id=settings.MAILCHIMP_LIST_ID, email_address=email) except: logger.exception('Failed to unsubscribe ' + email + ' from MailChimp list')
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import argv from os import path from mailsnake import MailSnake from mailsnake.exceptions import MailSnakeException mapi = MailSnake('XpV56E3xZK_pfIR7Jo0aTA', api='mandrill') fileName = path.dirname(path.abspath(__file__)) + '/password-reset.txt' file = open(fileName) text = file.read() file.close() text = text.replace("__TO_EMAIL_ADDRESS__", argv[1]) text = text.replace("__PASSWORD_RESET_URL__", argv[2]) try: response = mapi.messages.send(message={'html': text, 'subject': 'webnikki.jp パスワード再設定', 'from_email': '*****@*****.**', 'from_name': 'webnikki.jp 管理者', 'to':[{'email': argv[1], 'name': argv[1]}]}) # response == 'PONG!' except MailSnakeException: print 'An error occurred. :('
def __init__(self, apikey): self.api_key = apikey self.provider = MailSnake(self.api_key)
def send_message(template_name, subject, rcpts, context, tmpl_content=None, from_email='*****@*****.**'): """Send mandrill message. If DEBUG is set, recipients is forced to urlist crew, and mail is sent twice using TEST templates and normale templates; all mail are tracked in 'mailing' collection, stored with original recipients. """ tmpl_content = tmpl_content or {} m = MailSnake('234cb996-7286-4c08-a4ec-8993afe6495c', api='mandrill') global_merge_vars = [{ 'name': unicode(k), 'content': unicode(v) } for k, v in context.iteritems()] if not isinstance(rcpts, (list, tuple)) and not DEBUG: logging.info('Cannot send mail, no recipients') return recipients = [{ 'email': rcpt_email, 'name': rcpt_name } for rcpt_email, rcpt_name in rcpts] tmpl_content_ = [{ 'name': k, 'content': v } for k, v in tmpl_content.iteritems()] if DEBUG: debug_message = {'subject': u'TEST ~~~ {}'.format(subject)} db.mailing.insert({ 'rcpts': recipients, 'subject': subject, 'template': template_name }) recipients = [{'email': '*****@*****.**', 'name': 'Urlist Crew'}] google_analytics_domains = ["urlist.no-ip.org"] else: google_analytics_domains = ["urli.st"] message = { 'global_merge_vars': global_merge_vars, 'subject': subject, 'google_analytics_domains': google_analytics_domains, 'google_analytics_campaign': template_name, 'from_email': from_email, 'from_name': 'Urlist', 'to': recipients } def send(message, template_name): m.messages.send_template(template_name=template_name, template_content=tmpl_content_, message=message) send(message, template_name) if DEBUG: send(dict(message, **debug_message), 'test-{}'.format(template_name))
def reminder_emails(): print "DOING EMAILS NOW" mapi = MailSnake(settings.MANDRILL_API_KEY, api='mandrill') #get the context for this... context = {} members = Member.objects.filter(subscribed_reminder_email=True) #now we want to filter members for the correct reminder time that they want. for member in members: hour = member.reminder_email_time minute = 0 mem_time = member.current_time() mem_time_hour = mem_time.hour mem_time_minute = mem_time.minute/30 * 30 #deals with how long it takes to go through all if mem_time_hour != hour or mem_time_minute != minute: #this is the check for if we send the email. Currently, we want to continue context['username'] = member.user.username print "Sending for " + member.user.username #daily goals context['daily_goals'] = [] daily_goals = member.goals.filter(time_frame_len='d') for goal in daily_goals: goal.max_tf = goal.time_frames.all().latest() #here we should get the number and number left goal.finished = goal.max_tf.num_objs_finished() if goal.finished < goal.num_per_frame: context['daily_goals'].append(goal) context['daily_time'] = member.time_left_daily() #weekly goals context['weekly_goals'] = [] weekly_goals = member.goals.filter(time_frame_len='w') weekly_time = member.time_left_weekly() context['weekly_time'] = weekly_time days_left_weekly = (weekly_time - member.current_time()).days for goal in weekly_goals: goal.max_tf = goal.time_frames.all().latest() #here we should get the number and number left goal.finished = goal.max_tf.num_objs_finished() goal_difference = goal.num_per_frame - goal.finished under_week_deadline = True if goal_difference > days_left_weekly else False #or less than equal.... if under_week_deadline: context['weekly_goals'].append(goal) #monthly goals context['monthly_goals'] = [] monthly_goals = member.goals.filter(time_frame_len='m') monthly_time = member.time_left_monthly() context['monthly_time'] = monthly_time days_left_monthly = (monthly_time - member.current_time()).days for goal in monthly_goals: goal.max_tf = goal.time_frames.all().latest() #here we should get the number and number left goal.finished = goal.max_tf.num_objs_finished() goal_difference = goal.num_per_frame - goal.finished under_month_deadline = True if goal_difference > days_left_monthly else False #or less than equal.... if under_month_deadline: context['monthly_goals'].append(goal) if context['monthly_goals'] or context['weekly_goals'] or context['daily_goals']: subject = render_to_string('goals/reminder_email_subject.txt') body = render_to_string('goals/reminder_email_body.txt', context) print mapi.messages.send(message={'text':body, 'subject':subject, 'from_email':'*****@*****.**', 'from_name':'Streakflow Reminders', 'to':[{'email':member.user.email, 'name':member.user.username}]})
def __init__(self, template, message): self.template = template self.message = message self.mapi = MailSnake(settings.EMAIL_HOST_PASSWORD, api='mandrill') threading.Thread.__init__(self)
def complete(request): """ (3) Final checkout step, where the order is actually created from the basket. """ basket = Basket(request) # redirect back to a previous step if we missed anything... next = get_next_checkout_step(request, basket, CurrentPage.COMPLETE()) if next: return HttpResponseRedirect(next) # state or county if 'state' in basket.billing_address: county = basket.billing_address.get('state') else: county = basket.billing_address.get('county') # create account if requested if basket.signup: # create user account md5 = hashlib.md5() md5.update(basket.signup.get('email')) email = basket.signup.get('email') if User.objects.filter(email=email).count() > 0: messages.warning( request, 'There is already an account with this email: %s.' % email) return HttpResponseRedirect(reverse('shop.account.login')) user = User.objects.create(username=md5.hexdigest()[:30], first_name=basket.signup.get('first_name'), last_name=basket.signup.get('last_name'), email=email) # replace username with user id and set password user.username = unicode(user.id) user.set_password(basket.signup.get('password')) user.save() # create profile get_customer_model().objects.create( user=user, first_name=user.first_name, last_name=user.last_name, email=user.email, title=basket.billing_address.get('title'), address1=basket.billing_address.get('address1'), address2=basket.billing_address.get('address2'), address3=basket.billing_address.get('address3'), city=basket.billing_address.get('city'), county=county, postcode=basket.billing_address.get('postcode'), country=basket.billing_address.get('country'), telephone=basket.billing_address.get('telephone'), newsletter=basket.newsletter) # log user in login_user_without_password(request, user) basket.signup = None else: if request.user.is_anonymous(): user = None else: user = request.user # if specified, copy relevant information to customer's profile if user != None and basket.update_profile: user.first_name = basket.billing_address.get('first_name') user.last_name = basket.billing_address.get('last_name') user.save() customer = get_customer_model().objects.get(user=user) customer.address1 = basket.billing_address.get('address1') customer.address2 = basket.billing_address.get('address2') customer.address3 = basket.billing_address.get('address3') customer.city = basket.billing_address.get('city') customer.county = county customer.postcode = basket.billing_address.get('postcode') customer.country = basket.billing_address.get('country') customer.telephone = basket.billing_address.get('telephone') customer.save() # create single order order = get_order_model().create_from_basket(request, basket, user) # mailchimp if request.settings.mailchimp_enabled and basket.newsletter: email = basket.billing_address.get('email') first_name = basket.billing_address.get('first_name') last_name = basket.billing_address.get('last_name') person_name = (first_name, last_name) merge_vars = {'FNAME': " ".join(person_name)} ms = MailSnake(request.settings.mailchimp_api) try: ms.listSubscribe(id=request.settings.mailchimp_list_id, email_address=email, merge_vars=merge_vars) except: pass # redirect to order status page (payment from there...) basket.save() return HttpResponseRedirect( reverse('shop.order.status', args=[order.secret_id]))
from celery.decorators import task import logging REPORT_TO_EMAILS = [ { 'email': '*****@*****.**', 'type': 'to' }, ] log = logging.getLogger('debra.celery_status_checker') from mailsnake import MailSnake mailsnake_client = MailSnake(settings.MANDRILL_API_KEY, api='mandrill') def timeout(p): if p.poll() is None: try: p.kill() print 'Error: process taking too long to complete--terminating' except OSError as e: if e.errno != errno.ESRCH: raise @task(name="debra.celery_status_checker.check_celery_statuses", ignore_result=True) def check_celery_statuses():
def signup(request): try: username = request.POST.get("username") mail = request.POST.get("mail") password = request.POST.get("password") salt = 'predefined_key' # Possibly version specific? random_str = request.POST.get('skey')[:14] security_key = salt + hashlib.sha1( mail[::-1]).hexdigest().upper() + username.upper() + hashlib.sha1( hashlib.md5(password).hexdigest().upper()).hexdigest().upper() security_key = hashlib.sha1(random_str + security_key).hexdigest( ).upper() + '-' + hashlib.md5(security_key + random_str[::-1]).hexdigest().upper() security_key = security_key[:-1] security_key = random_str + security_key + "." skey = request.POST.get("skey") if skey == security_key: # Check if the user already exists existing = User.objects.filter( username__iexact=request.POST.get('username')) existing_mail = User.objects.filter( email__iexact=request.POST.get('mail')) if existing.exists(): raise IntegrityError() elif existing_mail.exists(): raise IntegrityError() else: temp = True try: user_check = User.objects.get( username=request.POST.get('username')) except: temp = False if temp == True: raise IntegrityError() user = User.objects.create_user(request.POST.get('username'), request.POST.get('mail'), request.POST.get('password')) user.groups.add(1) current_id = user.id user.save() person = Person.objects.get(user=user) from mailsnake import MailSnake mandrill = MailSnake('MshPu_5BxMs40_usJijM9Q', api='mandrill') message = { 'subject': 'Welcome to openi', 'to': [{ 'email': request.POST.get('mail') }], 'from_name': 'openi', 'from_email': '*****@*****.**', } content = [{'name': 'content1', 'content': '<p>email body</p>'}] mandrill.messages.send_template(template_name='signup', message=message, template_content=content) raise ImmediateHttpResponse( openiResponse( { 'username': request.POST.get('username'), 'user_id': current_id }, HttpCreated)) else: raise ImmediateHttpResponse( openiResponse( {'error': 'The specified key could not be verified.'}, HttpForbidden)) except IntegrityError: raise ImmediateHttpResponse( openiResponse({'error': 'Username or Email is already in-use'}, HttpConflict))