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: app.logger.error('Error subscribing: %s', e) flash('Sorry, an error occurred.')
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 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 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 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 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 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')
def __init__(self, apikey): self.api_key = apikey self.provider = MailSnake(self.api_key)
def mailchimp_webhook(request): ''' This view is called via a MailChimp webhook. ''' response = {} try: if request.GET['secret'] == 'WZnI3VUbvQxe4hjcRj8i5tEXpTyk7XMHgdRiu12SUVE': webhook_type = request.POST['type'] if webhook_type == 'subscribe': email = request.POST['data[email]'] # Update the user's preference if the user exists try: user = User.objects.get(email=email) except User.DoesNotExist: pass else: profile = user.get_profile() if profile: profile.newsletter = True profile.save(dispatch_signal=False) elif webhook_type == 'unsubscribe' or webhook_type == 'cleaned': email = request.POST['data[email]'] # Update the user's preference if the user exists try: user = User.objects.get(email=email) except User.DoesNotExist: pass else: profile = user.get_profile() if profile: profile.newsletter = False profile.save(dispatch_signal=False) elif webhook_type == 'upemail': old_email = request.POST['data[old_email]'] new_email = request.POST['data[new_email]'] mailsnake = MailSnake(settings.MAILCHIMP_API_KEY) # Update the user's preference if the user exists try: user = User.objects.get(email=old_email) except User.DoesNotExist: pass else: profile = user.get_profile() if profile: try: info = mailsnake.listMemberInfo(id=settings.MAILCHIMP_LIST_ID, email_address=(old_email,)) except: logger.exception('Failed to retrieve subscription info for ' + old_email + ' from MailChimp') else: if info['success'] == 1 and info['data'][0]['status'] == 'subscribed': profile.newsletter = True else: profile.newsletter = False profile.save(dispatch_signal=False) # Update the user's preference if the user exists try: user = User.objects.get(email=new_email) except User.DoesNotExist: pass else: profile = user.get_profile() if profile: try: info = mailsnake.listMemberInfo(id=settings.MAILCHIMP_LIST_ID, email_address=(new_email,)) except: logger.exception('Failed to retrieve subscription info for ' + new_email + ' from MailChimp') else: if info['success'] == 1 and info['data'][0]['status'] == 'subscribed': profile.newsletter = True else: profile.newsletter = False profile.save(dispatch_signal=False) response['success'] = 1 else: response['success'] = 0 except: response['success'] = 0 return HttpResponse(simplejson.dumps(response), mimetype='application/json')
def account_signup(self, request): email = request.session.get(settings.SIGNUP_EMAIL_SESSION_VAR, None) if email == '': raise Http404('Missing email address.') checkout = request.GET.get('checkout', False) == '1' form_class = self.get_account_signup_form() if request.method == 'POST': form = form_class(request.POST, initial={'checkout': checkout}) else: form = form_class(initial={ 'email': email, 'checkout': checkout }) form.configure(request) if request.method == 'POST': captcha = validate_captcha(request) if not captcha: messages.add_message(request, messages.ERROR, 'Please tick the checkbox at the bottom of the form to prevent SPAM.' ) if form.is_valid() and captcha: d = form.cleaned_data # create user account md5 = hashlib.md5() md5.update(d['email']) user = User.objects.create( username = md5.hexdigest()[:30], first_name = d['first_name'], last_name = d['last_name'], email = d['email'] ) # replace username with user id, set password and add user to list of customers user.username = unicode(user.id) user.set_password(d['password']) user.save() # create customer newsletter = 0 if request.settings.mailchimp_enabled: if d['newsletter']: person_name = (d['first_name'],d['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=d['email'], merge_vars=merge_vars) except: pass newsletter = d['newsletter'] customer = get_customer_model().objects.create( user=user, first_name = d['first_name'], last_name = d['last_name'], email=d['email'], title=d['title'], address1='', city='', county='', postcode='', country=d['country'], telephone='', newsletter=newsletter ) # log customer in login_user_without_password(request, user) # go to dashboard or deliver page messages.success(request, 'Thank you for signing up with us.') if d['checkout']: response = HttpResponseRedirect(reverse('shop.order.delivery')) else: response = HttpResponseRedirect(reverse('shop.account.index')) response.set_cookie('cubaneShopLogin', '1') return response return { 'account_section': True, 'is_signup_page': True, 'form': form }
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))
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}]})
#!/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. :('
import magic from email import message from mailsnake import MailSnake from celery.decorators import task from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.core.mail import mail_admins from django.core.cache import get_cache from debra.mongo_utils import notify_brand log = logging.getLogger('debra.mail_proxy') mailsnake_client = MailSnake(settings.MANDRILL_API_KEY, api='mandrill') mailsnake_admin_client = MailSnake(settings.MANDRILL_ADMIN_EMAIL_API_KEY, api='mandrill') mc_cache = get_cache('memcached') redis_cache = get_cache('redis') def upload_message_attachments_to_s3(message, attachments, b64=False): from masuka.image_manipulator import get_bucket, BUCKET_PATH_PREFIX s3_attachments = [] bucket = get_bucket('theshelf-email-attachments') try: for attachment in attachments: if type(attachment) == dict: filename = "%s_%s" % (message.id if message else datetime.datetime.now(),
from django import forms from django.conf import settings from mailsnake import MailSnake from mailsnake.exceptions import * key = MailSnake(settings.MAILCHIMP_API_KEY) list_sub = settings.MAILCHIMP_SUBSCRIBE_LIST_ID class SubscribeForm(forms.Form): list_id = list_sub email = forms.EmailField(label='E-mail') name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') def save(self): try: key.ping() except MailSnakeException: return False except ListAlreadySubscribedException: return False except: return False else: return key.listSubscribe( id=self.list_id, email_address=self.cleaned_data['email'], name=self.cleaned_data['name'], merge_vars={'FNAME': self.cleaned_data['name'], 'LNAME': self.cleaned_data['last_name']
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 __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]))
def request(self, command, **kwargs): ms = MailSnake(self.key) try: return getattr(ms, command)(**kwargs) except AttributeError: raise ValueError("That's not a valid mailchimp command")
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():
import json import os from datetime import datetime from firebase import firebase from mailsnake import MailSnake from mailsnake.exceptions import * batches = [] ms = MailSnake('0ffe3bf01dafb47436bf81d47c6dae22-us4') firebaseapp = firebase.FirebaseApplication( 'https://internproject.firebaseio.com', None) firebaseapp.authentication = firebase.FirebaseAuthentication( 'pRUr2LaCuvLszUCioUYRFvbDpMYAzaOZd4joMkNJ', '*****@*****.**') signedup_on_firebase = firebaseapp.get('/email-signup', None) last_pull_datetime = datetime.fromtimestamp( int(os.getenv('last_sync_stamp', datetime(2013, 06, 25).strftime('%s')))) date_format = '%m/%d/%Y %X' signedup_recently = [ user['email'] for user in signedup_on_firebase.values() if datetime.strptime(user['submit_time'], date_format) > last_pull_datetime ] for e in signedup_recently: