Esempio n. 1
0
def ajax_participation_remove(request, challenge_id):
    if request.is_ajax():
        ctx = {}
        participation_id = request.POST.get("participation_id", "")
        value = request.POST.get("action_id", "")
        text = request.POST.get("text", "")

        try:
            participation = Participation.objects.get(pk=participation_id)
        except:
            return HttpResponse("An error has been encountered")

        ctx.update({
            "user": participation.user,
            "challenge": participation.challenge,
            "participation": participation, })

        if value == PARTICIPATION_REMOVE_MODE.REMOVE_APPLICATION:
            participation.status = PARTICIPATION_STATE.CANCELLED_BY_ADMIN
            template_name = "challenge_participation_removed"
        elif value == PARTICIPATION_REMOVE_MODE.REJECT_APPLICATION:
            participation.status = PARTICIPATION_STATE.CONFIRMATION_DENIED
            template_name = "challenge_participation_rejected"

        participation.cancellation_text = text
        participation.date_cancelled = datetime.now()
        participation.save()

        send_templated_mail(
            template_name=template_name,
            from_email="*****@*****.**",
            recipient_list=[participation.user.email, ],
            context=ctx, )
        return HttpResponse()
    return HttpResponse("An error has been encountered!")
Esempio n. 2
0
 def handle(self, *args, **options):
     message = options.get('message')
     verbosity = options.get('verbosity')
     get_template('templated_email/notice.email')
     if not message:
         raise CommandError(_('message must be included in options'))
     # get all users
     users = User.objects.all()
     for user in users:
         name = user.get_full_name()
         if not name or len(name) == 0:
             name = user.email
         if verbosity:
             self.stdout.write(_(
                 'Emailing name: %(name)s, email: %(email)s')
                 % {'name': name, 'email': user.email})
         # send each email separately so users cannot see eachother
         send_templated_mail(
             template_name='notice',
             from_email='*****@*****.**',
             recipient_list=[user.email],
             context={
                 'username': user.username,
                 'full_name': name,
                 'message': message
             }, )
Esempio n. 3
0
 def send_to_email(self, email, context={}):
     send_templated_mail(
         template_name=self.get_template_name(),
         from_email=settings.DEFAULT_FROM_EMAIL,
         recipient_list=[email],
         context=context
     )
Esempio n. 4
0
  def create_tasks(self):    
    print "create_tasks"
    now  = helper.get_now()
    user=User()
    sitebanner=SiteBanner.objects.all()

    for sitebanners in sitebanner:
      user_id=sitebanners.user_id
      print user_id
      user=User.objects.get(id=user_id)
      print user
      email=user.email
      print email
      name=user.username
      print name
      result=sitebanners.enddate
      print "result", result
      if result:       
        subject="Your " +  " Your banner will be removed from today onwards"
				
      sitebanners.admin_status = False 
      send_templated_mail(
						template_name = 'welcome',
						subject = "subject",
						from_email = '*****@*****.**',
						recipient_list = [email],
						context = {'name':name},
							)
      print "mail send" 
      sitebanners.save()
Esempio n. 5
0
def send_email(request, template, from_, to, context):
    send_templated_mail(template_name=template,
                        from_email=from_,
                        recipient_list=to,
                        context=context,
                        )
    return HttpResponse()
Esempio n. 6
0
    def save(self, *args, **kwargs):
        # New model
        NEW = False
        if not self.pk:
            NEW = True
            self.token = self.generate_token()

            send_templated_mail(
                template_name='new_signup',
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[self.email],
                context={
                    'token': self.token,
                    'name': self.name,
                    'email': self.email,
                    'postcode': self.postcode,
                }
            )
        
        m = super(SignUp, self).save(*args, **kwargs)
        
        if NEW:
            # For now, just update the whole coultry.  More to follow.
            area, created = LocalInfo.objects.get_or_create(type='country', name='UK')
            for key in self._fields:
                if key in self.COLLECT:
                    if bool(getattr(self, key)):
                        count = area.info.get(key, 0) + 1
                        area.info[key] = count
                    else:
                        area.info[key] = area.info.get(key, 0)
            area.save()
        
        return m
Esempio n. 7
0
def send_promote_customer_to_staff_email(staff):
    site = Site.objects.get_current()
    ctx = {'domain': site.domain, 'site_name': site.name}
    send_templated_mail(template_name='dashboard/staff/promote_customer',
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        recipient_list=[staff.email],
                        context=ctx)
Esempio n. 8
0
    def form_valid(self, form):
        obj = form.save(commit=False)

        password = User.objects.make_random_password()
        obj.set_password(password)

        obj.is_active = True
        obj.save()

        # Now log in this user
        user = authenticate(email=obj.email, password=password)
        if user is not None:
            login(self.request, user)
        else:
            raise Exception("Could not auth recently created user")

        # send password in email
        send_templated_mail(
            template_name='accounts/new_user_email',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            context = {
                'user': user,
                'password': password,
                'BASE_URL': settings.BASE_URL
            }
        )

        # where to next? If we have a next go there, otherwise home
        next_url = self.request.POST.get('next')
        if next_url:
            return redirect(next_url)
        else:
            return redirect('home')
Esempio n. 9
0
    def form_valid(self, form):
        obj = form.save(commit=False)

        password = User.objects.make_random_password()
        obj.set_password(password)

        obj.is_active = True
        obj.save()

        # Now log in this user
        user = authenticate(email=obj.email, password=password)
        if user is not None:
            login(self.request, user)
        else:
            raise Exception("Could not auth recently created user")

        # send password in email
        send_templated_mail(template_name='accounts/new_user_email',
                            from_email=settings.DEFAULT_FROM_EMAIL,
                            recipient_list=[user.email],
                            context={
                                'user': user,
                                'password': password,
                                'BASE_URL': settings.BASE_URL
                            })

        # where to next? If we have a next go there, otherwise home
        next_url = self.request.POST.get('next')
        if next_url:
            return redirect(next_url)
        else:
            return redirect('home')
Esempio n. 10
0
def send_email(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        servico = request.POST.get('servico')
        message = request.POST.get('message')
        forma_contato = request.POST.get('forma-contato')
        telefone = request.POST.get('telefone')

        send_templated_mail(template_name='email',
                            from_email='email',
                            recipient_list=[
                                '*****@*****.**',
                                os.environ['EMAIL_RECIPIENT_ACCOUNT']
                            ],
                            context={
                                'nome': name,
                                'email': email,
                                'servico': servico,
                                'mensagem': message,
                                'forma_contato': forma_contato,
                                'telefone': telefone
                            })

        return HttpResponseRedirect('/')

    return render(request, 'core/index.html', {})
Esempio n. 11
0
def send_staff_order_confirmation(order_pk, redirect_url):
    """Send order confirmation email."""
    staff_email_data = collect_staff_order_notification_data(
        order_pk, STAFF_CONFIRM_ORDER_TEMPLATE, redirect_url
    )
    if staff_email_data["recipient_list"]:
        send_templated_mail(**staff_email_data)
Esempio n. 12
0
def rspwn(request):
    form = RspwnForm()
    if request.method == 'POST':
        form = RspwnForm(request.POST)
        if form.data['login']:
            u = User.objects.filter(username=form.data['login']).last()
            if not u:
                u = User.objects.filter(email=form.data['login']).last()
            if not u:
                return render(request, 'noaccount.html', {"form": form})
            user = u
            import os, random, string
            length = 13
            chars = string.ascii_letters + string.digits + '!@#$%^&*()'
            random.seed = (os.urandom(1024))
            password = ''.join(random.choice(chars) for i in range(length))
            user.set_password(password)
            user.save()
            send_templated_mail(
                template_name="rspwn.html",
                from_email='*****@*****.**',
                recipient_list=[user.email],
                context={'password': password},
            )
            return render(request, 'rspwnsucess.html')
    return render(request, 'rspwn.html', {"form": form})
Esempio n. 13
0
def test_send_set_password_customer_email(customer_user, site_settings):
    site = site_settings.site
    uid = urlsafe_base64_encode(force_bytes(customer_user.pk))
    token = default_token_generator.make_token(customer_user)
    logo_url = build_absolute_uri(static("images/logo-light.svg"))
    password_set_url = build_absolute_uri(
        reverse("account:reset-password-confirm",
                kwargs={
                    "token": token,
                    "uidb64": uid
                }))
    ctx = {
        "logo_url": logo_url,
        "password_set_url": password_set_url,
        "site_name": site.name,
    }
    send_templated_mail(
        template_name="dashboard/customer/set_password",
        from_email=site_settings.default_from_email,
        recipient_list=[customer_user.email],
        context=ctx,
    )
    assert len(mail.outbox) == 1
    sended_message = mail.outbox[0].body
    assert password_set_url in sended_message
Esempio n. 14
0
def upload_banner(request):
	if request.POST.get('price',False):
		uploadbanner=SiteBanner()
		uploadbanner.price=request.POST.get('price',request.COOKIES.get('price'))
		uploadbanner.position=request.POST.get('position',request.COOKIES.get('position'))
		uploadbanner.pageurl=request.POST.get('pageurl',request.COOKIES.get('pageurl'))
		uploadbanner.banner=request.FILES.get('banner',request.COOKIES.get('banner'))
		uploadbanner.link=request.POST['link']
		uploadbanner.save()
		send_templated_mail(
			  template_name = 'banner',
			  subject = 'Uplaod Banner',
			  from_email = '*****@*****.**',
			  recipient_list = [request.user.email ],
			  context={
					   'user': request.user,
										   
			  },
		  )  
		response=HttpResponseRedirect("/payment/")
		response.set_cookie( 'price', uploadbanner.price )
		response.set_cookie( 'position', uploadbanner.position )
		response.set_cookie( 'banner', uploadbanner.banner )
		response.set_cookie( 'pageurl', uploadbanner.pageurl )
	#field9 is payu success variable
	# this if condition for after success of payment
	elif 'field9' in request.POST:
		message="Your data succesfully uploaded"
		response = render_to_response("uploadbanner.html",{'message':message},context_instance=RequestContext(request))
	else:
		message="Something went to wrong"
		response = render_to_response("uploadbanner.html",{'message':message},context_instance=RequestContext(request))   
	return response
def email_user_report_link(to, **extra_context):
    """
    When: A user requests "email" report
    :param user:
    :param url:
    :return:
    """
    if to is not list:
        to = [to]

    message = "<p>You requested a copy of %s</p>" % extra_context[
        'report_title']
    message += "<p>Click the button below or copy this link:</p>"
    message += "<p>%s</p>" % extra_context['url']

    context = {
        "message": message,
        "subject": "Download %s" % extra_context['report_title'],
        "action_cta": "Download Report",
        "action_url": extra_context['url'],
        **extra_context
    }

    send_templated_mail(
        template_name='simple_action',
        from_email='*****@*****.**',
        recipient_list=to,
        context=context,
    )
Esempio n. 16
0
 def handle(self, *args, **options):
     projects = Project.objects.all()
     number_emails = 0
     task_type = TaskType.objects.get(title="phone")
     for project in projects:
         delta = project.create_date.replace(tzinfo=None) - datetime.now()
         if delta.days == -6 and project.funding_advisor:
             number_emails = number_emails + 1
             task = Task(title="Day Six in Finance Check Call",
                         scheduled_date=date.today(),
                         completion=False,
                         task_type=task_type,
                         project=project,
                         user=project.sales_rep.user)
             task.save()
             send_templated_mail(
                 template_name='financeday6',
                 from_email='*****@*****.**',
                 recipient_list=[project.sales_rep.user.email, '*****@*****.**'],
                 context={
                     'project': project,
                     'task': task
                 },
             )
     self.stdout.write('Sent "%s" emails' % number_emails)
Esempio n. 17
0
def send_mail_task(content, from_mail, to_mails, template):
    send_templated_mail(
        template_name=template,
        from_email=from_mail,
        recipient_list=to_mails,
        context=content
    )
Esempio n. 18
0
def contact(request):
	"""
	Contact us
	"""
	success_msg = None
	if request.POST:
		contact = ContactForm()
		contact.name = request.POST.get('name', '')
		contact.email = request.POST.get('email', '')
		contact.mobile = request.POST.get('phone', '')
		contact.message = request.POST.get('message', '')
		contact.save()
		try:
			send_templated_mail(
					template_name='contact',
					from_email='*****@*****.**',
					recipient_list=[request.POST.get('email')],
					context={
						'username':request.POST.get('name', 'Guest')
					},
			)
		except:
			email = None
		success_msg = "Your request successfully sent to Admin. We will revert back you soon"
	return render_to_response('contact_us.html',{'success_msg':success_msg}, context_instance=RequestContext(request))
Esempio n. 19
0
    def send_matches(self, request, obj, client, lawyers, form):
        """
        Sent the matches email.
        """
        logger.info('Sending project matches email')

        recipient = '"{name}" <{email}>'.format(name=client.get_full_name(), email=client.email)

        intro_content = '\r\n'.join(['<h2 style="color: #6c797c !important; font-family: \'Helvetica Neue\', Helvetica, Arial, sans-serif; font-size: 16px; font-weight: normal; line-height: 1.5em; margin: 0 0 25px; padding: 0;">{para}</h2>'.format(para=para) for para in form.cleaned_data.get('intro', '').split("\r\n") if para.strip() != ''])

        email = Bunch(
            template_name='project_matches',
            from_email=SITE_EMAIL,
            recipient_list=[recipient],
            bcc=['*****@*****.**'],
            context={
                'lawyers': lawyers,
                'to_name': client.first_name,
                'intro_content': intro_content,
                'url': reverse('dashboard:overview'),
            }
        )

        if settings.DEBUG:
            email.pop('bcc')

        send_templated_mail(**email)
Esempio n. 20
0
def order(request):
    if request.is_ajax() and request.method == 'POST':
        form = OrderForm(request.POST or None)
        if form.is_valid():
            order = form.save()
            info = json.loads(order.summary_info)
            trip = get_object_or_None(Trips, id=order.cont_id)
            moneta_form = MonetaForm(
                account_id=MONETA_ACCOUNT_ID,
                transaction_id=order.id,
                amount='100.00',
                use_signature=True,
                integrity_check_code='tripper',
                description=u'Оплата экскурсии: %s' % trip.name
            )
            send_templated_mail(
                template_name='order',
                from_email=DEFAULT_FROM_EMAIL,
                recipient_list=[order.email],
                context={
                    'fullname':order.fullname,
                    'info': json.loads(order.summary_info) if order.summary_info else {},
                    'trip': trip
                },
            )
            data = {
                'success': True,
                'form': moneta_form.as_p()
            }
            return HttpResponse(json.dumps(data), mimetype="application/json")
    raise Http404
Esempio n. 21
0
 def irun(self):
     # Recover current state to go on where we ended last time,
     # or start from the beginning.
     if Setting.notify_bans and settings.VBM_NOTIFICATIONS_EMAIL:
         ban_submissions = BanSubmission.objects.filter(launched_at__isnull=False)
         if Setting.notify_bans_task_status is not None:
             ban_submissions = ban_submissions.filter(pk__gt=Setting.notify_bans_task_status)
         # Prepare data.
         submissions_log = [{
                 'id': ban_submission.id,
                 'launched_at': ban_submission.launched_at,
                 'user': ban_submission.user.human_name,
                 'ban_type': ban_submission.human_ban_type_name,
                 'expression': ban_submission.expression,
                 'target_type': ban_submission.target.human_class_name,
                 'target': ban_submission.target.human_name,
                 'items': ban_submission.items.all(),
             } for ban_submission in ban_submissions.iterator()]
         if len(submissions_log) > 0:
             # Send e-mail.
             send_templated_mail(
                 template_name='varnish-bans-manager/core/bans/submissions',
                 from_email=settings.DEFAULT_FROM_EMAIL,
                 recipient_list=[settings.VBM_NOTIFICATIONS_EMAIL],
                 bcc=settings.DEFAULT_BCC_EMAILS,
                 context={
                     'base_url': settings.VBM_BASE_URL,
                     'submissions_log': submissions_log,
                 },
             )
             # Store last seen id to keep track of our position.
             Setting.notify_bans_task_status = submissions_log[-1]['id']
Esempio n. 22
0
def test_send_set_password_email(staff_user, site_settings):
    site = site_settings.site
    uid = urlsafe_base64_encode(force_bytes(staff_user.pk)).decode()
    token = default_token_generator.make_token(staff_user)
    logo_url = build_absolute_uri(static('images/logo-light.svg'))
    password_set_url = build_absolute_uri(
        reverse(
            'account:reset-password-confirm',
            kwargs={'token': token, 'uidb64': uid}))
    ctx = {
        'logo_url': logo_url,
        'password_set_url': password_set_url,
        'site_name': site.name}
    send_templated_mail(
        template_name='dashboard/staff/set_password',
        from_email=DEFAULT_FROM_EMAIL,
        recipient_list=[staff_user.email],
        context=ctx)
    assert len(mail.outbox) == 1
    generated_link = reverse(
        'account:reset-password-confirm',
        kwargs={
            'uidb64': uid,
            'token': token})
    absolute_generated_link = build_absolute_uri(generated_link)
    sended_message = mail.outbox[0].body
    assert absolute_generated_link in sended_message
Esempio n. 23
0
def toggle_comment_favorite(request, username, comment_id):
    thread = MPTTComment.objects.get(pk=comment_id)
    video = thread.content_object
    user = request.user

    is_favorite = Action.objects.actor(user,
                                       verb='added to favorites',
                                       action_object_object_id=comment_id)

    if is_favorite:
        action_name = 'removed from favorites'
        is_favorite.delete()
    else:
        action_name = 'added to favorites'

    action.send(user,
                verb=action_name,
                action_object=thread, target=video)

    if thread.user.id != user.id and thread.user.email:
        send_templated_mail(
            template_name='favorites-notification',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[thread.user.email],
            context={
                'comment': thread,
                'site': Site.objects.get_current(),
                'recipient': thread.user,
                'user': user,
            })
    return HttpResponse()
Esempio n. 24
0
def send_account_create_confirmation_email(context, recipient):
    ctx = get_email_base_context()
    ctx.update(context)
    send_templated_mail(template_name='account/account_create',
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        recipient_list=[recipient],
                        context=ctx)
Esempio n. 25
0
def email(request):
    users = User.objects.all()
    if request.method == 'POST':
        emailUsers = User.objects.filter(id__in = request.POST.getlist('emailUsers'))
        for i in emailUsers:
            logger.info('Send email to - {0}'.format(i.email))
            try:
                template = request.POST.get('emailUrl')
                send_templated_mail(
                    template_name = template,
                    from_email = u'Магазин ShinUK <*****@*****.**>',
                    recipient_list = [i.email],
                    context = {
                        'text': request.POST.get('emailText', ''),
                        'user': i
                    }
                )
                logger.info('Ok sended email to - {0}'.format(i.email))
            except:
                logger.info('Errror!!! send email to - {0}'.format(i.email))
                messages.error(request, u'Ошибка при отправке письма с уведомлением!')
        return redirect('/ladmin/email/')
    else:
        pass
    return render_to_response('ladmin/email.html', locals(), context_instance = RequestContext(request))
def update_profile(request):
    user_form = UserForm(request.POST, instance=request.user)
    profile_form = ProfileForm(request.POST, instance=request.user.profile)
    if request.method == 'POST':
        if user_form.is_valid():
            user_form.save()
            profile_form.save()
            user = request.user
            npswd = request.POST.get('password')
            if npswd != '':
                send_templated_mail(
                    template_name="rspwn.html",
                    from_email='*****@*****.**',
                    recipient_list=[user.email],
                    context={
                        'password': npswd
                    },

                )
                user.set_password(request.POST.get('password'))
            user.save()
        else:
            return HttpResponseRedirect('/nicechange/')
            messages.error(request, 'Please correct the error below.')
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })
Esempio n. 27
0
 def send_smart_email(self,
                      recipient,
                      template_name,
                      from_email=settings.DEFAULT_FROM_EMAIL,
                      extra={}):
     recipient_list = [
         recipient if isinstance(recipient, basestring) else recipient.email
     ]
     context = {
         'recipient': recipient,
         'review': self,
         'site_name': settings.MILLER_TITLE,
         'site_url': settings.MILLER_SETTINGS['host'],
     }
     context.update(extra)
     try:
         send_templated_mail(template_name=template_name,
                             from_email=from_email,
                             recipient_list=recipient_list,
                             context=context)
     except Exception as e:
         logger.exception(e)
     else:
         logger.debug('review {pk:%s} email %s sent' %
                      (self.pk, template_name))
def send_daily_template_mail(user, day):
    tomorrow = day + timedelta(1)
    day_start = datetime.combine(day, time())
    day_end = datetime.combine(tomorrow, time())
    posts = Post.objects.\
        filter(created__lte=day_end, created__gte=day_start).\
        filter(author__in=user.friends.values_list('user2'))
    import os
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ava.png')
    with open(path, 'r') as fin:
        ava_image = fin.read()
    inline_image = InlineImage(filename="ava.png", content=ava_image)

    send_templated_mail(
        template_name='daily',
        from_email='*****@*****.**',
        recipient_list=[user.email],
        context={
            'username': user.username,
            'posts': posts,
            'date': day,
            'ava_image': inline_image,
        },
        create_link=True
        # Optional:
        # cc=['*****@*****.**'],
        # bcc=['*****@*****.**'],
        # headers={'My-Custom-Header':'Custom Value'},
        # template_prefix="my_emails/",
        # template_suffix="email",
    )
Esempio n. 29
0
def contact(request):
    EMAIL_CUSTOMER_ATTENDANT  = getattr(settings, 'EMAIL_CUSTOMER_ATTENDANT', '*****@*****.**')
    DEFAULT_FROM_EMAIL = getattr(settings, 'DEFAULT_FROM_EMAIL', '*****@*****.**')
    DOMAINURL = getattr(settings, 'DOMAINURL', 'http://dirplace.com/')
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            message = 'Please reply to: ' + cd['email'] + '\n\n\n'
            message = message + cd['description']
            send_templated_mail(
                    template_name='contact-notification',
                    from_email=DEFAULT_FROM_EMAIL,
                    recipient_list=[EMAIL_CUSTOMER_ATTENDANT],
                    context={
                        'message':message,
                    },
            )
            return redirect('/dirplace/contact_thanks/')
    else:
        form = ContactForm()
    c = {
            'form': form
    }
    return render_to_response ('dirplace/contact-us.html', c, context_instance =  RequestContext(request),)
Esempio n. 30
0
def email_user_magic_link(to, **extra_context):
    if to is not list:
        to = [to]
    message = "<p>You may now login by clicking the login button below.</p>"
    url = "%s/r?p=%s&token=%s" % (settings.APP_FRONTEND, extra_context['page_id'], extra_context['token'])
    context = {
        "message": message,
        "subject": "Login to access %s" % extra_context['page_title'],
        "action_cta": "Login",
        "action_url": url,
        **extra_context
    }

    kwargs = {
        "reply_to": extra_context["reply_to"]
    }
    from_email = '%s <*****@*****.**>' % extra_context['author_name']

    send_templated_mail(
        template_name='simple_action',
        from_email=from_email,
        recipient_list=to,
        context=context,
        **kwargs
    )
Esempio n. 31
0
def _send_set_password_email(recipient_email, password_set_url, template_name):
    send_kwargs, ctx = get_email_context()
    ctx["password_set_url"] = password_set_url
    send_templated_mail(template_name=template_name,
                        recipient_list=[recipient_email],
                        context=ctx,
                        **send_kwargs)
Esempio n. 32
0
def email_user_password_reset_request(to, **extra_context):
    """
    When: When a user attempts to reset their password
    To: The user who wants their password reset.
    :param to:
    :param extra_context:
    :return:
    """
    if to is not list:
        to = [to]

    message = "<p>You requested to reset your password.</p>"
    message += "<p>If you didn't request a new password, please respond to this email.</p>"

    url = "%s/reset/%s" % (settings.APP_FRONTEND, extra_context['token'])

    context = {
        "message": message,
        "subject": "Reset Capitol Zen Password",
        "action_cta": "Reset Password",
        "action_url": url,
        **extra_context
    }

    send_templated_mail(
        template_name='simple_action',
        from_email='Capitol Zen Password <*****@*****.**>',
        recipient_list=to,
        context=context,
    )
Esempio n. 33
0
def ajax_invite_friends(request):
    """
        Send email invitation to friends
    """
    # we've got a POST request which means user wants to invite friends
    if request.POST:
        try:
            recipients = request.POST.get('recipients', "")

#todo: schedule batch action to offload main webserver
            for r in recipients.split("\n"):
                for addr in r.split(" "):
                    for email in addr.split(","):
                        try:
                            email = email.strip()
                            if email.find("@") == -1:
                                continue

                            send_templated_mail(
                                template_name='invite_friends',
                                from_email="Difio <%s>" % settings.DEFAULT_FROM_EMAIL,
                                recipient_list=[email],
                                context={
                                    'username':request.user.username,
                                    'full_name':request.user.get_full_name(),
                                },
                            )
                        except:
                            continue
        except:
            pass

    return HttpResponse("SUCCESS", mimetype='text/plain')
Esempio n. 34
0
 def emit(self, record):
     try:
         from logs.models import ErrorLog
         logEntry =ErrorLog()
         logEntry.level = record.levelname 
         logEntry.error_msg = record.getMessage(), record.exc_info      
         logEntry.ip_address = globals.ip
         # print "logEntry.ip_address", logEntry.ip_address
         logEntry.page = record.args, record.lineno, record.pathname 
         logEntry.datetime = datetime.datetime.now()
         logEntry.user = record.request.user
         logEntry.admin_status = 'open'
         logEntry.save()
     except:            
         pass
     
     try:
         if record.levelname == 'ERROR':
            send_templated_mail(
                 template_name='error',
                 from_email=settings.DEFAULT_FROM_EMAIL,
                 recipient_list=[],
                 context={
                          'errorlevel': record.levelname,
                          'error_msg': [record.getMessage(), record.exc_info],
                          'error_ip': globals.ip,
                          'error_user': record.request.user,
                          'error_line' : [record.lineno, record.pathname],
                 },
             ) 
     except:
         pass  
Esempio n. 35
0
def ContactView(request):
    if request.method == 'POST':
        nome = request.POST.get('nome')
        telefone = request.POST.get('telefone')
        assunto = request.POST.get('assunto')
        email = request.POST.get('email')
        mensagem = request.POST.get('mensagem')

        #print(name)
        #print(email)
        #print(mensagem)
        send_templated_mail (
            template_name='email',
            from_email='email',
            recipient_list=['*****@*****.**'],
            context={
                'nome': nome,
                'telefone': telefone,
                'assunto': assunto,
                'email': email, 
                'mensagem': mensagem,
            }
        )
        return HttpResponseRedirect('/')
    return render(request,'index/index.html',{})
Esempio n. 36
0
def send_email(template_name, payload, destination_email=""):
    '''Emails all active users from the gmail set up for the server. Text
    is the primary format but alternative html is rendered and sent as
    well.
    
    '''
    active_users = User.objects.filter(is_active=True)
    active_users_email = []
    for user in active_users:
        active_users_email.append(user.email)
    if template_name == 'inventory_results':
        send_templated_mail(
            template_name=template_name,
            from_email='Cabana Server',
            recipient_list=active_users_email,
            context=payload,
            template_suffix="html",
        )
    elif template_name == 'ulon_expired':
        CHO_email = Group.objects.get(
            name='Chemical Hygiene Officer (CHO)').user_set.all()[0].email
        send_templated_mail(
            template_name=template_name,
            from_email='Cabana Server',
            recipient_list=[destination_email],
            context=payload,
            cc=[CHO_email],
        )
Esempio n. 37
0
    def form_valid(self, form):
        user = form.save()
        user.is_active = True
        user.save()
        registration = Registration.objects.create(user=user)

        #     user = User.objects.get(registration__uuid=uuid, type='register')
        #     user.is_active = True
        #     user.save()
        #     user.registration.delete()
        #
        messages.info(self.request, 'Registration successfull')
        send_templated_mail(
            template_name='registration',
            # substitute your e-mail adress
            from_email='*****@*****.**',
            recipient_list=[
                form.cleaned_data['email'],
            ],
            context={
                'url_name': 'activation',
                'url_param': 'key',
                'registration': registration,
                'current_site': Site.objects.get_current(),
                'base_url': settings.SITE_URL,
            },
        )
        return super(RegisterView, self).form_valid(form)
Esempio n. 38
0
def mail(from_e, tolist, message, template, contexts):
    configs = EmailConfig.objects.filter(default=True)
    if configs.count() > 0:
        conf = configs.first()
        from django.conf import settings
        settings.DEFAULT_FROM_EMAIL = conf.default_from_email
        settings.EMAIL_HOST = conf.email_host
        settings.EMAIL_HOST_USER = conf.email_host_user
        settings.EMAIL_HOST_PASSWORD = conf.email_host_password
        settings.EMAIL_PORT = conf.email_port
        settings.EMAIL_USE_TLS = conf.email_use_tls
        send_templated_mail(
            template_name=template,
            from_email=from_e,
            recipient_list=tolist,
            context=contexts,
            fail_silently=False,
        )
    else:
        from django.conf import settings
        settings.DEFAULT_FROM_EMAIL = "*****@*****.**"
        settings.EMAIL_HOST = "smtp.gmail.com"
        settings.EMAIL_HOST_USER = "******"
        settings.EMAIL_HOST_PASSWORD = "******"
        settings.EMAIL_PORT = 587
        settings.EMAIL_USE_TLS = True
        send_templated_mail(
            template_name=template,
            from_email=from_e,
            recipient_list=tolist,
            context=contexts,
            fail_silently=False,
        )
Esempio n. 39
0
 def handle(self, *args, **options):
     projects = Project.objects.all()
     number_emails = 0
     task_type = TaskType.objects.get(title="phone")
     for project in projects:
         delta = project.create_date.replace(tzinfo=None) - datetime.now()
         if delta.days == -6 and project.funding_advisor:
             number_emails = number_emails + 1
             task = Task(title="Day Six in Finance Check Call",
                         scheduled_date=date.today(),
                         completion=False,
                         task_type=task_type,
                         project=project,
                         user=project.sales_rep.user)
             task.save()
             send_templated_mail(
                 template_name='financeday6',
                 from_email='*****@*****.**',
                 recipient_list=[
                     project.sales_rep.user.email,
                     '*****@*****.**'
                 ],
                 context={
                     'project': project,
                     'task': task
                 },
             )
     self.stdout.write('Sent "%s" emails' % number_emails)
Esempio n. 40
0
def send_state_email(current, template_name):
    # For owner
    owner = current.site.created_by
    context = {
        'site': current.site,
        'history': current,
        'owner': owner,
        'base_url': get_base_url(),
    }
    send_templated_mail(
        template_name=template_name,
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[owner.email],
        context=context,
    )
    # For extra
    for recipient in current.site.recipients.filter(enabled=True):
        context = {
            'site': current.site,
            'history': current,
            'owner': {'get_full_name': 'Subscriber'},
            'base_url': get_base_url(),
        }
        send_templated_mail(
            template_name=template_name,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[recipient.email],
            context=context,
        )
Esempio n. 41
0
  def form_valid(self, form):
    user = form.save()
    user.is_active = True
    user.save()
    registration = Registration.objects.create(user=user)
    
#     user = User.objects.get(registration__uuid=uuid, type='register')
#     user.is_active = True
#     user.save()
#     user.registration.delete()
#     
    messages.info(self.request, 'Registration successfull')
    send_templated_mail(
      template_name='registration',
      # substitute your e-mail adress
      from_email='*****@*****.**',
      recipient_list=[form.cleaned_data['email'],],
      context={
        'url_name': 'activation',
        'url_param': 'key',
        'registration': registration,
        'current_site': Site.objects.get_current(),
        'base_url': settings.SITE_URL,
      },
    )
    return super(RegisterView, self).form_valid(form)
Esempio n. 42
0
def test_send_set_password_email(staff_user, site_settings):
    site = site_settings.site
    uid = urlsafe_base64_encode(force_bytes(staff_user.pk))
    token = default_token_generator.make_token(staff_user)
    logo_url = build_absolute_uri(static("images/logo-light.svg"))
    password_set_url = build_absolute_uri(
        reverse(
            "account:reset-password-confirm", kwargs={"token": token, "uidb64": uid}
        )
    )
    ctx = {
        "logo_url": logo_url,
        "password_set_url": password_set_url,
        "site_name": site.name,
    }
    send_templated_mail(
        template_name="dashboard/staff/set_password",
        from_email=DEFAULT_FROM_EMAIL,
        recipient_list=[staff_user.email],
        context=ctx,
    )
    assert len(mail.outbox) == 1
    generated_link = reverse(
        "account:reset-password-confirm", kwargs={"uidb64": uid, "token": token}
    )
    absolute_generated_link = build_absolute_uri(generated_link)
    sended_message = mail.outbox[0].body
    assert absolute_generated_link in sended_message
Esempio n. 43
0
def send_email_message(message_name, to_email, context=None):
    send_templated_mail(
        template_name=EMAIL_MESSAGE_TEMPLATES[message_name],
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[to_email],
        context=context or {}
    )
Esempio n. 44
0
def generate_and_send_verification_token(request):
    if request.method == "POST":
        data = json.loads(request.body)
        email = data['email']
        userName = data['username']

        def token_generator(string_length=7):
            """Returns a random string of length string_length."""
            random = str(
                uuid.uuid4())  # Convert UUID format to a Python string.
            random = random.upper()  # Make all characters uppercase.
            random = random.replace("-", "")  # Remove the UUID '-'.
            return random[0:string_length]  # Return the random string.

        user_token = token_generator()
        print('userToken', user_token)
        VerificationKey.objects.create(useremail=email, token=user_token)
        send_templated_mail(
            template_name='verification',
            from_email='*****@*****.**',
            recipient_list=[email],
            context={
                'token': user_token,
                'username': userName,
            },
        )
        return HttpResponse(status=200)
Esempio n. 45
0
def beta_confirm(email, **kwargs):
    """
    Send out email confirming that they requested an invite.
    """

    templates_folder = setting('BETA_EMAIL_TEMPLATES_DIR', 'hunger')
    templates_folder = os.path.join(templates_folder, '')
    from_email = setting('EMAIL_HOST_USER')
    if templates_folder == 'hunger':
        file_extension = 'email'
    else:
        file_extension = None

    context_dict = kwargs.copy()
    if templated_email_available:
        send_templated_mail(
            template_dir=templates_folder,
            template_name='beta_confirm',
            file_extension=file_extension,
            from_email=from_email,
            recipient_list=[email],
            context=context_dict,
        )
    else:
        plaintext = get_template(os.path.join(templates_folder, 'beta_confirm.txt'))
        html = get_template(os.path.join(templates_folder, 'beta_confirm.html'))
        subject, to = 'You requested an invite!', email
        text_content = plaintext.render(Context())
        html_content = html.render(Context())
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
                                     headers={'From': 'Mailer <%s>' % from_email})
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Esempio n. 46
0
 def form_valid(self, form):
     response = super(SubscriberView, self).form_valid(form)
     if self.request.is_ajax():
         data = {
             'email': self.object.email,
             'name': self.object.name,
         }
         print(data)
         send_templated_mail(template_name='subscriber_noreply',
                             from_email=settings.DEFAULT_FROM_EMAIL,
                             recipient_list=[self.object.email],
                             context={
                                 'full_name': self.object.name,
                             })
         send_templated_mail(template_name='new_subscriber',
                             from_email=settings.DEFAULT_FROM_EMAIL,
                             recipient_list=[settings.DEFAULT_FROM_EMAIL],
                             context={
                                 'full_name': self.object.name,
                                 'email': self.object.email,
                             })
         # msg = """Dear %s, thanks for your subscribing. We will notify you about all news on our site.
         # Regards, AdaviBeauty.""" % self.object.name
         # with mail.get_connection() as connection:
         #     mail.EmailMessage(
         #         "No reply, AdaviBeauty", msg, settings.DEFAULT_FROM_EMAIL, [self.object.email],
         #         connection=connection
         #     ).send()
         return JsonResponse(data)
     else:
         return response
Esempio n. 47
0
    def send_email_to_assignee(self, template_name, extra={}):
        """
    send email to assignee
    """
        recipient = self.assignee.email

        context = {
            'username': self.assignee.username,
            'site_name': settings.MILLER_TITLE,
            'story': self.story,
            'reviews_url':
            settings.MILLER_SETTINGS['host'] + '/login/?next=/reviews',
            'site_name': settings.MILLER_TITLE,
            'site_url': settings.MILLER_SETTINGS['host'],
            'decision': self.decision
        }
        # update with extra field according to email template.
        context.update(extra)

        if recipient:
            logger.debug('review {pk:%s} sending email to user {pk:%s}...' %
                         (self.pk, self.assignee.pk))
            send_templated_mail(template_name=template_name,
                                from_email=settings.DEFAULT_FROM_EMAIL,
                                recipient_list=[self.assignee.email],
                                context=context)
            # from_email=settings.DEFAULT_FROM_EMAIL,
        else:
            logger.debug(
                'review {pk:%s} cannot send email to assignee, user {pk:%s} email not found!'
                % (self.pk, self.assignee.pk))
Esempio n. 48
0
def ajax_participation_accept(request, challenge_id):
    if request.is_ajax():
        participation_id = request.POST.get("participation_id", "")
        try:
            participation = Participation.objects.get(pk=participation_id)
        except:
            return HttpResponse("An error has been encountered")

        participation.status = PARTICIPATION_STATE.CONFIRMED
        participation.date_accepted = datetime.now()
        participation.save()

        send_templated_mail(
            template_name="challenge_participation_accepted",
            from_email="*****@*****.**",
            recipient_list=[participation.user.email, ],
            context={
                "user": participation.user,
                "challenge": participation.challenge,
                "subject": _("You were accepted for %(challenge_name)s")
                           % {"challenge_name": participation.challenge.name},
                "challenge_url": participation.challenge.get_full_url(request),

            }, )
        return HttpResponse()
    return HttpResponse("An error has been encountered!")
Esempio n. 49
0
def test_send_set_password_email(staff_user, site_settings):
    site = site_settings.site
    uid = urlsafe_base64_encode(force_bytes(staff_user.pk))
    token = default_token_generator.make_token(staff_user)
    logo_url = build_absolute_uri(static('images/bringall-logo.png'))
    password_set_url = build_absolute_uri(
        reverse("account:reset-password-confirm",
                kwargs={
                    "token": token,
                    "uidb64": uid
                }))
    ctx = {
        "logo_url": logo_url,
        "password_set_url": password_set_url,
        "site_name": site.name,
    }
    send_templated_mail(
        template_name="dashboard/staff/set_password",
        from_email=DEFAULT_FROM_EMAIL,
        recipient_list=[staff_user.email],
        context=ctx,
    )
    assert len(mail.outbox) == 1
    generated_link = reverse("account:reset-password-confirm",
                             kwargs={
                                 "uidb64": uid,
                                 "token": token
                             })
    absolute_generated_link = build_absolute_uri(generated_link)
    sended_message = mail.outbox[0].body
    assert absolute_generated_link in sended_message
Esempio n. 50
0
 def save(self, force_insert=False, force_update=False, *args, **kwargs):
     is_new = self.id is None
     super(Project, self).save(*args, **kwargs)
     if is_new:
         Document.objects.create(project=self, title='Act Notes', internal=True)
         Document.objects.create(project=self, title='SRTO', internal=True)
         if self. financing_cash > 0:
             Document.objects.create(project=self, title='Cash')
         if self.financing_hloc > 0:
             Document.objects.create(project=self, title='HELOC')
         if self.financing_401k > 0:
             Document.objects.create(project=self, title='401K')
         if self.financing_pension > 0:
             Document.objects.create(project=self, title='Pension')
         if self.financing_ira > 0:
             Document.objects.create(project=self, title='IRA')
         if self.financing_stocksbonds > 0:
             Document.objects.create(project=self, title='Stocks and Bonds')
         if not User.objects.filter(username=self.email).count():
             user = User.objects.create_user(self.email, self.email, 'erF213')
             user.last_name = self.last_name
             user.first_name = self.first_name
             user.save()
             self.customers_user = user
             self.save()
         send_templated_mail(
             template_name='new_app',
             from_email='*****@*****.**',
             recipient_list=[self.email],
             context={
                 'project': self,
             },
         )
Esempio n. 51
0
def test_send_set_password_email(staff_user, site_settings):
    site = site_settings.site
    uid = urlsafe_base64_encode(force_bytes(staff_user.pk)).decode()
    token = default_token_generator.make_token(staff_user)
    logo_url = build_absolute_uri(static('images/logo-document.svg'))
    password_set_url = build_absolute_uri(
        reverse('account:reset-password-confirm',
                kwargs={
                    'token': token,
                    'uidb64': uid
                }))
    ctx = {
        'logo_url': logo_url,
        'password_set_url': password_set_url,
        'site_name': site.name
    }
    send_templated_mail(template_name='dashboard/staff/set_password',
                        from_email=DEFAULT_FROM_EMAIL,
                        recipient_list=[staff_user.email],
                        context=ctx)
    assert len(mail.outbox) == 1
    generated_link = reverse('account:reset-password-confirm',
                             kwargs={
                                 'uidb64': uid,
                                 'token': token
                             })
    absolute_generated_link = build_absolute_uri(generated_link)
    sended_message = mail.outbox[0].body
    assert absolute_generated_link in sended_message
Esempio n. 52
0
def email_share(context):
    context_data = context.get(DATA_KEY, None)
    video_id = context.get('video_id', None)
    video = Video.objects.get(slug=video_id)
    share_with_email = context_data.get('shareWithEmail', None)
    shared_by = None

    if context_data.get('username', None):
        user = auth.models.User.objects.get(username=context_data['username'])
    else:
        user = context.get('user', None)

    if user and not isinstance(user, auth.models.AnonymousUser):
        action.send(user, verb='shared', action_object=video)
        shared_by = user

    if share_with_email:
        send_templated_mail(
            template_name='share-email',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[share_with_email],
            context={
                'shared_by': user,
                'video': video,
                'site': Site.objects.get_current(),
                'shared_by': shared_by,
            })
Esempio n. 53
0
    def formset_valid(self, formset):
        """
        This function is called when the formset is deemed valid.
        An email is sent to all email fields which are filled in.
        If the request is done via ajax give json back with a success message, otherwise
        redirect to the success url.
        """
        protocol = self.request.is_secure() and 'https' or 'http'
        date_string = date.today().strftime('%d%m%Y')

        # Get the current site or empty string
        try:
            current_site = Site.objects.get_current()
        except Site.DoesNotExist:
            current_site = ''

        for form in formset:
            if form in formset.deleted_forms:
                continue

            first_name = form.cleaned_data.get('first_name')

            email = form.cleaned_data.get('email')
            tenant_id = self.request.user.tenant_id
            hash = sha256('%s-%s-%s-%s' % (
                tenant_id,
                email,
                date_string,
                settings.SECRET_KEY
            )).hexdigest()
            invite_link = '%s://%s%s' % (protocol, current_site, reverse_lazy('invitation_accept', kwargs={
                'tenant_id': tenant_id,
                'first_name': first_name,
                'email': email,
                'date': date_string,
                'hash': hash,
            }))

            # Email to the user
            send_templated_mail(
                template_name='invitation',
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[form.cleaned_data['email']],
                context={
                    'current_site': current_site,
                    'full_name': self.request.user.full_name,
                    'name': first_name,
                    'invite_link': invite_link,
                }
            )

            post_intercom_event(event_name='invite-sent', user_id=self.request.user.id)

        if is_ajax(self.request):
            return HttpResponse(anyjson.serialize({
                'error': False,
                'html': _('The invitations were sent successfully'),
            }), content_type='application/json')
        return HttpResponseRedirect(self.get_success_url())
Esempio n. 54
0
def post_save_transaction(signal, instance, **kwargs):
    send_templated_mail(
        template_name='send_heart',
        from_email=settings.FROM_EMAIL,
        recipient_list=[instance.receiver.user.email],
        context={
            'transaction': instance
        })
Esempio n. 55
0
def borrow(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    today = datetime.date.today()
    context = {'book': book}
    if request.method == 'POST':
        book_request = BookRequest(book=book, requester=request.user)
        form = BookRequestForm(request.POST, instance=book_request)
        if form.is_valid():
            request_object = form.save()
            review_url = request.build_absolute_uri(reverse('books:review_requests'))
            send_templated_mail(
                    template_name='book_requested',
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[book.submitter.email],
                    context={
                        'book': book,
                        'book_request': book_request,
                        'review_url': review_url,
                        })
            return HttpResponseRedirect(reverse('books:my_requests'))
        else:
            context['form'] = form
            return render(request, 'books/borrow.html', context)
    else:
        # Since available_until can be None:
        if not book.available_until:
            is_still_available = True
        else:
            is_still_available = today <= book.available_until

        # Check if there are pending requests
        if not book.status == 'A':
            # Check if the book is actually available (not held,
            # borrowed or expired).
            # TODO: Make it  possible to borrow a book  in the future,
            # after the book is returned.
            context['error'] = 'not_available'
            #elif request.user == book.submitter:
            #    context['error'] = 'is_submitter'
        elif request.user == book.holder:
            context['error'] = 'is_holder'
        elif not is_still_available:
            context['error'] = 'expired'
        elif today < book.available_from:
            context['error'] = 'not_yet'
        elif book.available_to != get_gender(request.user):
            context['error'] = 'gender'

        # If the more serious errors arenot present, we can check for
        # warnings and prepare the form:
        if not 'error' in context:
            previous_requests = BookRequest.objects.filter(status='P')
            if previous_requests:
                context['warning'] = 'pending_requests'
            form = BookRequestForm()
            context['form'] = form

        return render(request, 'books/borrow.html', context)
Esempio n. 56
0
    def form_valid(self, form):
        """
        Register a new user.
        """
        # Do not accept any valid form when registration is closed.
        if not settings.REGISTRATION_POSSIBLE:
            messages.error(self.request, _('I\'m sorry, but I can\'t let anyone register at the moment.'))
            return redirect(reverse_lazy('login'))

        # Create and save user
        user = LilyUser.objects.create_user(
            email=form.cleaned_data['email'],
            password=form.cleaned_data['password'],
            first_name=form.cleaned_data['first_name'],
            preposition=form.cleaned_data['preposition'],
            last_name=form.cleaned_data['last_name'],
        )

        user.is_active = False
        user.save()

        # Add to admin group
        account_admin = Group.objects.get_or_create(name='account_admin')[0]
        user.groups.add(account_admin)

        # Get the current site
        try:
            current_site = Site.objects.get_current()
        except Site.DoesNotExist:
            current_site = ''

        # Generate uidb36 and token for the activation link
        uidb36 = int_to_base36(user.pk)
        token_generator = PasswordResetTokenGenerator()
        token = token_generator.make_token(user)

        # Send an activation mail
        # TODO: only create/save contact when e-mail sent successfully
        send_templated_mail(
            template_name='activation',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[form.cleaned_data['email']],
            context={
                'current_site': current_site,
                'protocol': self.request.is_secure() and 'https' or 'http',
                'user': user,
                'uidb36': uidb36,
                'token': token,
            }
        )

        # Show registration message
        messages.success(
            self.request,
            _('Registration completed. I\'ve sent you an email, please check it to activate your account.')
        )

        return self.get_success_url()
    def test_with_connection_in_args(self):
        mocked_connection = Mock()
        send_templated_mail(*self.TEST_ARGS, connection=mocked_connection,
                            **self.TEST_KWARGS)

        kwargs = dict(self.TEST_KWARGS)
        del kwargs['template_prefix']
        del kwargs['template_suffix']
        mocked_connection.send.assert_called_with(*self.TEST_ARGS, **kwargs)
Esempio n. 58
0
 def sendmail(self, title, email,ctx):
     current_site = Site.objects.get(id=1),
     send_templated_mail(
            template_name = 'product_alert',
            from_email = '*****@*****.**',
            recipient_list = [email],
            context = ctx,
       )
     print "mail successfully"
Esempio n. 59
0
def send_promote_customer_to_staff_email(staff_pk):
    staff = User.objects.get(pk=staff_pk)
    ctx = get_email_base_context()
    ctx['dashboard_url'] = build_absolute_uri(reverse('dashboard:index'))
    send_templated_mail(
        template_name='dashboard/staff/promote_customer',
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[staff.email],
        context=ctx)