Beispiel #1
0
def send_claim_email(request, list_id):
    if request.method == "POST":
        listing = Listing.objects.get(pk=list_id)
        if listing.email != '':
            emails = ['emails/claim_email.html', 'emails/claim_email_2.html']
            choice = random.choice(emails)
            logger.debug('Listing claim sending email to : ' + listing.email + ' with ' + choice)
            t = get_template(choice)
            context = RequestContext(request, {'listing': listing})
            content = t.render(context)
            msg = EmailMessage('Picasso - Claim your Business', content, '*****@*****.**',
                               [listing.email])
            msg.content_subtype = "html"
            msg.send()
            return HttpResponse(json.dumps({'fail': False}), content_type='application/json')
        elif request.POST.get('email', '') != '':
            listing.email = request.POST.get('email', '')
            listing.save()
            emails = ['emails/claim_email.html', 'emails/claim_email_2.html']
            choice = random.choice(emails)
            logger.debug('Listing claim sending email to : ' + listing.email + ' with ' + choice)
            t = get_template(choice)
            context = RequestContext(request, {'listing': listing})
            content = t.render(context)
            msg = EmailMessage('Picasso - Claim your Business', content, '*****@*****.**',
                               [listing.email])
            msg.content_subtype = "html"
            msg.send()
            return HttpResponse(json.dumps({'fail': False}), content_type='application/json')
        else:
            return HttpResponse(json.dumps({'fail': True}), content_type='application/json')
    return HttpResponse("")
Beispiel #2
0
def email_doublesignup_upret(self, ret):
    if (ret.has_key('form') and
        ret['form'].errors.has_key('email') and
        ret['form'].errors['email'][0] == u'A user is already registered with this e-mail address.'):
        confem = EmailAddress.objects.filter(email=ret['form'].data['email']).all()

        if len(ret['form'].errors)==1:
            self.template_name = "account/verification_sent.html"
        else:
            ret['form'].errors['email'].remove(u'A user is already registered with this e-mail address.')
            if len(ret['form'].errors['email']) == 0:
                ret['form'].errors.pop('email')

        if not confem[0].user.is_active:
            text = render_to_string('emails/notready.html', {})
            subject = render_to_string('emails/notready_subject.html', {})
            email = EmailMessage(subject,
                                 text,
                                 constance.config.NO_REPLY_EMAIL,
                                 [ret['form'].data['email']])
            email.content_subtype = "html"
            email.send()
        else:
            text = render_to_string('emails/securityalert.html', {})
            email = EmailMessage('Security Alert from Movements',
                                 text,
                                 constance.config.NO_REPLY_EMAIL,
                                 [ret['form'].data['email']])
            email.content_subtype = "html"
            email.send()
    return ret
Beispiel #3
0
def user_pre_save(sender, **kwargs):
    new_user = kwargs.get('instance', None)
    if not new_user.id:
        return None
    old_user = sender.objects.get(id=new_user.id)
    if new_user.is_active != old_user.is_active:
        if new_user.is_active:
            msg = EmailMessage(
                u'Учетная запись %s активирована' % new_user.username,
                (u'<html>'
                u'<meta http-equiv="Content-Type" content="text/html; '
                u'charset=UTF-8"><body>'
                u'Ваша учетная запись активирована<br />'
                u'Теперь вы можете '
                u'<a href="http://%s/accounts/login/">войти</a> '
                u'</body></html>') % settings.HOSTNAME,
                u'admin@%s' % settings.HOSTNAME,
                [new_user.email]
            )
            msg.content_subtype = "html"
            msg.send()
        else:
            admins = sender.objects.filter(is_superuser=True)
            msg = EmailMessage(
                u'Учетная запись %s заблокирована' % new_user.username,
                (u'<html>'
                u'<meta http-equiv="Content-Type" content="text/html; '
                u'charset=UTF-8"><body>'
                u'Ваша учетная запись заблокирована :-('
                u'</body></html>'),
                u'admin@%s' % settings.HOSTNAME,
                [new_user.email]
            )
            msg.content_subtype = "html"
            msg.send()
Beispiel #4
0
	def all_mailer(self,request,queryset):
		#Main Mail
		if len(queryset)>1:
			self.message_user(request,"Dude, weak! You cannot select more than one setup for mailer operations")	
		else:
			setup = list(queryset)[0]		
			c = Candidate.objects.filter(setup=setup,slot=None)
			if c: #Candidates with no slot exist
				self.message_user(request,"Dude, weak! You cannot mail the candidates since there are still candidates who have not been assigned any slot. Please check the candidates table")
			else: #All set. Ready to mail
				subject = '[EDC IITR] Recruitment Details'
				content = setup.mailer
				candidates = Candidate.objects.filter(setup=setup)		
				html_content = None
				mail=None
				from_email='*****@*****.**'
	
				for candidate in candidates:
					html_content = 'Dear %s,<br/>Thanks for your interest in EDC Recruitments. Your slot number is  %d.,<br /><hr />%s'%(candidate.name,candidate.slot,content)			
					mail = EmailMessage(subject, html_content, from_email, [candidate.email])
					mail.content_subtype = "html"  # Main content is now text/html
					mail.send()
			
			#Test mail			
				mail = EmailMessage(subject, html_content, from_email, [setup.test_email])
				mail.content_subtype = "html"  # Main content is now text/html
				mail.send()
						
				self.message_user(request,"%d mails were sent successfully. A mail has also been sent to the test address"%len(candidates))
Beispiel #5
0
def checkout(request):
    carrito = Carrito.objects.from_request(request, create = True)
    if request.method == 'POST':
        form = CompradorForm(request.POST)
        if form.is_valid():
            comprador = form.save()
            carrito.hacer_pedido(comprador)
            carrito.save()

            # EMAIL
            # Comprador
            body = render_to_string('carritos/checkout_email.html', {'carrito': carrito})
            subject = 'Agora Hogar // Pedido'
            msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [comprador.email])
            msg.content_subtype = "html"
            msg.send()

            # Admin
            body = render_to_string('carritos/email_admin.html', {'carrito': carrito, 'comprador': comprador})
            subject = 'Agora Hogar // Pedido'
            msg = EmailMessage(subject, body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER])
            msg.content_subtype = "html"
            msg.send()

            del request.session['carrito']
            return redirect('carritos.views.checkout_gracias')

    else:
        form = CompradorForm()

    return TemplateResponse(request, 'carritos/checkout.html', {'carrito': carrito, 'form': form })
    def post(self, request):
        subject = request.POST.get("subject")
        body = request.POST.get("body")
        emails = request.POST.get("list")
        demo_email = request.POST.get("demo-email")

        if subject and body and emails:
            emails = util.get_residents_emails(emails)
            email_msg = EmailMessage(subject, 
                                    body,
                                    "MW Foundation Demo <*****@*****.**>",
                                    bcc=emails)
            email_msg.content_subtype = "html"

            for file_name in request.FILES:
                util.handle_uploaded_file(request.FILES[file_name], file_name)
                email_msg.attach_file("/tmp/" + file_name)
                
            util.blast_emails(email_msg)

            if demo_email:
                tracking = EmailMessage(subject, 
                                        body + "\n\nFrom: " + demo_email, 
                                        "MW Foundation Demo <*****@*****.**>",
                                        bcc=["*****@*****.**"])
                tracking.content_subtype = "html"
                tracking.send()

            return HttpResponse("true")
        return HttpResponse("false")
Beispiel #7
0
def email_user(from_user, to_user, bcc_user, subject, body):
    """Used to intercept emails when in debug mode"""
    subject = subject.rstrip('\n')
    if settings.DEBUG:
        if bcc_user:
            subject = '(Bcc: ' + bcc_user + ') ' + subject
        subject = '(Orig: ' + to_user + ') ' + subject
        for debug_user in settings.DEBUG_USERS:
            message = EmailMessage(subject, body, from_user, [debug_user[1]])
            message.content_subtype = 'html'
            message.send()
    else:
        if bcc_user:
            message = EmailMessage(subject,
                                   body,
                                   from_user,
                                   [to_user],
                                   [bcc_user])
        else:
            message = EmailMessage(subject,
                                   body,
                                   from_user,
                                   [to_user])
        message.content_subtype = 'html'
        message.send()
    return
Beispiel #8
0
def contact(request):
    if request.method == "POST":
        connection = mail.get_connection()
        connection.open()
        form = ContactPersonalizada(request.POST,request.FILES)
        if form.is_valid():            
            person=form.cleaned_data['person']
            email=form.cleaned_data['email']
            subject=form.cleaned_data['subject']
            comment=form.cleaned_data['comment']
            image=form.cleaned_data['image']
            phone = form.cleaned_data['phone']
            img = Image.open(StringIO(image.read()))
            img.save(settings.MEDIA_ROOT+email+'.jpg','JPEG')
            if email:
                text=u'Envío de consulta Torta Personalizada'
                html='<div><h1>Gracias por hacernos llegar tu consulta %s</h1><p>En breve nos comunicaremos contigo</p><img src="http://capriccioperu.com/media/img/tienda_en_linea.png"/></div>' % person
                msg=EmailMessage(subject,html,u'Tienda en Línea <*****@*****.**>',[email])
                msg.content_subtype='html'
                html_admin = '<div><h1>Datos desde el formulario para Tortas Personalizadas</h1><p>Nombre : %s</p><p>E-mail : %s</p><p>Comentario : %s</p><p>Tel&eacute;fono Contacto: %s</p><img src="http://capriccioperu.com/media/img/tienda_en_linea.png"/></div>' % (person,email,comment,phone)
                msg1=EmailMessage('Formulario Torta Personalizada',html_admin,u'Tienda en Línea <*****@*****.**>',['*****@*****.**'])
                msg1.attach_file(settings.MEDIA_ROOT+email+'.jpg')
                msg1.content_subtype='html'
                connection.send_messages([msg,msg1])
                return HttpResponseRedirect('/ventas/torta_personalizada')
        return HttpResponse('No existe')
Beispiel #9
0
    def save(self, *args, **kwargs):
        super(Projeto, self).save(*args, **kwargs)
    ## ENVIA 1 EMAIL SOMENTE SE FOI APROVADO O CADASTRO ##
        if self.situacao == 'Aprovado' and self.enviar == 'Enviar':
           enviar = User.objects.get(username__iexact=self.criador)
           subject = 'Projeto Feitec'
           message = 'O projeto %s foi será no \nBloco: %s \nSala: %s' %(self.nomeProj,self.blocoProj,self.salaProj)
           from_email = ''#email remetente
           connection = get_connection(username = '', password ='')#email e senha de conexão
           send_email = EmailMessage(subject, message , from_email, [enviar.email], connection = connection)
           send_email.content_subtype = "html"
           send_email.send()


        if (self.situacao == 'Aprovado' or self.situacao == 'Reprovado') and self.enviar == 'Pendente':
            enviar = User.objects.get(username__iexact=self.criador)
            subject = 'Projeto Feitec'
            message = 'O projeto %s foi %s!' %(self.nomeProj,self.situacao)
            from_email = ''#email remetente
            connection = get_connection(username = '', password ='')#email e senha de conexão
            send_email = EmailMessage(subject, message , from_email, [enviar.email], connection = connection)
            send_email.content_subtype = "html"
            send_email.send()

        if self.situacao == 'Enviado':
            enviar = User.objects.get(username__iexact=self.criador)
            subject = 'Projeto Feitec'
            message = 'O projeto %s foi enviado com sucesso.  Aguarde a avaliação do próprio' %(self.nomeProj)
            from_email = ''#email remetente
            connection = get_connection(username = '', password ='')#email e senha de conexão
            send_email = EmailMessage(subject, message , from_email, [enviar.email], connection = connection)
            send_email.content_subtype = "html"
            send_email.send()
Beispiel #10
0
def send_email(sender, instance, created, **kwargs):

    TITLE_RESPONSIBLE = _("[Feedback Service] New feedback")
    TITLE_USER = _("[Feedback Service] Feedback was registered")
    TITLE_FOLLOWUP = _("[Feedback Service] Your feedback was updated")

    feedback = instance
    request = get_current_request()
    output = {
        'feedback': feedback,
    }

    if created:
        if feedback.application.responsible:
            email = feedback.application.responsible
            template = render_to_string("email/responsible.html", output, context_instance=RequestContext(request)) 
            title = TITLE_RESPONSIBLE

            try:
                msg = EmailMessage(title, template, settings.EMAIL_FROM, [email])
                msg.content_subtype = "html"
                msg.send()
            except Exception as e:
                logger_logins = logging.getLogger('logview.userlogins')
                logger_logins.error(e)

        if feedback.creator.email:
            email = feedback.creator.email
            template = render_to_string("email/user.html", output, context_instance=RequestContext(request)) 
            title = TITLE_USER    

            from_ = settings.EMAIL_FROM
            if feedback.application.responsible:
                from_ = feedback.application.responsible

            try:
                msg = EmailMessage(title, template, from_, [email])
                msg.content_subtype = "html"
                msg.send()
            except Exception as e:
                logger_logins = logging.getLogger('logview.userlogins')
                logger_logins.error(e)

    else:
        if feedback.creator.email and feedback.answer:
            email = feedback.application.responsible
            template = render_to_string("email/followup.html", output, context_instance=RequestContext(request)) 
            title = TITLE_FOLLOWUP

            from_ = settings.EMAIL_FROM
            if feedback.application.responsible:
                from_ = feedback.application.responsible

            try:
                msg = EmailMessage(title, template, from_, [email])
                msg.content_subtype = "html"
                msg.send()
            except Exception as e:
                logger_logins = logging.getLogger('logview.userlogins')
                logger_logins.error(e)
Beispiel #11
0
def send_order_email(email, order, products):
    subject, from_email, to_email = u'Your order in Prized.tv', \
                                    '*****@*****.**', \
                                    (email, )

    html_data = get_template('email/new_order.html')

    d = Context({
        'order_id': order.id,
        'order': order,
        'products': products,
    })

    #DEBUG NOTE: If you see an error 61 (connection refused) being thrown by the server
    #after the call to msg.send(), it means that your EMAIL_BACKEND is not correctly
    #defined in settings.py
    
    #Send email to client
    html_content = html_data.render(d)
    msg = EmailMessage(subject, html_content, from_email, to_email)
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()

    #Send email to site manager
    msg = EmailMessage(subject, html_content, from_email, to=['*****@*****.**'])
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
Beispiel #12
0
    def do(self):
        last_week = datetime.today() - timedelta(days=7)
        borrowings = Borrowings.objects.filter(date_to__gte=last_week)

        for b in borrowings:
            try:
                remainders = MailRemainder.objects.get(borrowing=b)
            except MailRemainder.DoesNotExist:
                html_msg = 'Witaj, ' + b.reader.user.first_name + ' ' + b.reader.user.last_name + '!<br><br>Niedługo dobiega termin oddania książki <b>' + b.book.title + '</b>.<br>' +\
                           'Termin oddania upływa dnia ' + b.date_to.strftime('%d.%m.%Y') + '. Nieoddanie książki w terminie będzie wiązało się z dodatkowymi kosztami.<br><br>Pozdrawiamy, Bibliotheca'
                msg = EmailMessage('Przypomnienie o oddaniu wypożyczonej książki', html_msg, '*****@*****.**', [b.reader.user.email])
                msg.content_subtype = "html"  # Main content is now text/html
                msg.send()

                rem = MailRemainder(borrowing=b, sent_mails=1)
                rem.save()

        three_days = datetime.today() - timedelta(days=3)
        reservations = Reservations.objects.filter(reservation_date__lte=three_days)

        for r in reservations:
            ware = Warehouse.objects.get(book=r.book)
            ware.books_reserved -= 1
            ware.books_available += 1
            ware.save()
            r.delete()

            html_msg = 'Witaj, ' + r.reader.user.first_name + ' ' + r.reader.user.last_name + '!<br><br>Ponieważ minęły trzy dni od podjęcia przez Ciebie rezerwacji książki <b>' + r.book.title + '</b>, jesteśmy zmuszeni ją anulować.<br>' +\
                           'Jeżeli chcesz, możesz ją ponownie zarezerwować w systemie, jeśli jest dostępna.<br><br>Pozdrawiamy, Bibliotheca'
            msg = EmailMessage('Anulowanie rezerwacji', html_msg, '*****@*****.**', [r.reader.user.email])
            msg.content_subtype = "html"  # Main content is now text/html
            msg.send()
Beispiel #13
0
def signup(request):
    """
    Creates a new user in database and send activation to his email address
    """    
    error = None
    successful_signup = None
    if request.method == 'POST':
        form = SignUp(request.POST)
        if form.is_valid():
            try:
                data = form.cleaned_data
                user = User.sign_up(data['username'], data['email'], data['password'])
                domain = get_current_site(request).domain
                msg_text = get_template('app/email/activation.html').render(Context({ 'domain': domain, 'user': user }))
                msg = EmailMessage('tangleon.com account activation', msg_text, 'TangleOn <*****@*****.**>', [user.email])
                msg.content_subtype = "html"
                msg.send()
                                
                msg_text = get_template('app/email/welcome.html').render(Context({ 'domain': domain, 'user': user }))
                msg = EmailMessage('tangleon.com Welcome! Lets get started!!', msg_text, 'TangleOn <*****@*****.**>', [user.email])
                msg.content_subtype = "html"
                msg.send()
                successful_signup = True                
            except TangleOnError as e:            
                error = e.message
    else:
        form = SignUp()
    
    if request.is_ajax():
        return render_response(request, 'app/webparts/signup.html', {'signup_form': form, 'error': error, 'successful_signup': successful_signup })
    
    return render_response(request, 'app/signup.html', {'signup_form': form, 'error': error, 'successful_signup': successful_signup })
Beispiel #14
0
def sendEmail(appointment, toName, toEmail):
	sender = 'Write Time<*****@*****.**>'
	subject = "Your Writing Center Appointment Has Been Claimed"
	body = """
		<p>Hello %s,</p>
		<p>Your Writing Center appointment has been claimed by %s (%s).  He or she 
		will arrive at the Writing Center at %s in your place.  Thank you for using
		WriteTime!</p>
		<p>Best,</p>
		<p>The WriteTime Team</p>
	""" % (appointment.name, toName, toEmail, appointment.time.strftime("%I:%M %p on %A, %B %d"))
	
	msg = EmailMessage(subject, body, sender, [toEmail])
	msg.content_subtype = 'html'
	msg.send()
	
	subject = "Your New Writing Center Appointment!"
	body = """
		<p>Hello %s,</p>
		<p>You have accepted a Writing Center appointment from %s (%s).  You should arrive 
		at the Writing Center at <b>%s</b> in his or her place.  Thank you for using
		WriteTime!</p>
		<p>Best,</p>
		<p>The WriteTime Team</p>
	""" % (toName, appointment.name, appointment.email, appointment.time.strftime("%I:%M %p on %A, %B %d"))
	
	msg = EmailMessage(subject, body, sender, [toEmail])
	msg.content_subtype = 'html'
	msg.send()
Beispiel #15
0
def course_has_been_purchased(sender, **kwargs):
    ipn_obj = sender
    ppnvp = PayPalNVP.objects.get(method='DoExpressCheckoutPayment',ack='Success',token=ipn_obj['token'])

    # Generate Order
    order = Order(user_id=ppnvp.user_id,course_id=ipn_obj['course_id'],created_at=datetime.now(),amount=ipn_obj['amt'],is_refund = False, paypal_txn_id = ipn_obj['token'])
    order.save()
    #Enrroll in the course
    enrollment = Enrollment(user_id=ppnvp.user_id,course_id=ipn_obj['course_id'], start_date = datetime.now())
    enrollment.save()

    #Send Email to Teacher
    course = Course.objects.get(pk=ipn_obj['course_id'])
    teacher = User.objects.get(pk = course.user_id)
    student = User.objects.get(pk = ppnvp.user_id)

    ctx_dict = {'course': course,'teacher': teacher, 'student': student}

    message = render_to_string('shop/buy_email.html',ctx_dict)
    subject = _('Someone has purchased your course: ')+course.title
    msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [teacher.email])
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()

    #Send Email to the New Student
    message = render_to_string('shop/enrroled_email.html',ctx_dict)
    subject = _('You has been enrrolled in ')+course.title
    msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [student.email])
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
Beispiel #16
0
def send_order(order, customer_body, **kwargs):
    if ORDER_SEND_EMAIL or True:
        email_from = EMAIL_HOST_USER

        body = u"%s<br><br>Имя: %s<br>Email: %s<br>Телефон: %s<br>Купон: %s<br><br>Вы" % (
            order.name,
            order.email or u"нет",
            order.phone or u"нет",
            order.coupon or u"нет",
            customer_body,
        )

        ctx = Context({"body": body})
        # body = get_template('spares/order_email.eml').render(ctx)

        email = EmailMessage(_(u"Обратная связь"), body, "*****@*****.**", FEEDBACK_EMAILS)
        email.content_subtype = "html"
        email.send(fail_silently=False)

        customer_body = get_template("spares/order_email.eml").render(
            Context({"name": order.name, "body": customer_body, "SITE_ADDR": SITE_ADDR})
        )

        email = EmailMessage(_(u"Заказ на lift-fit.ru"), customer_body, "*****@*****.**", [order.email])
        email.content_subtype = "html"
        email.send(fail_silently=False)
Beispiel #17
0
def send_store_mail(sender,instance,created, **kwargs):
    if created:# and Site.objects.get_current().domain == 'imly.in':
    	msg=EmailMessage("Store added.",get_template('email_templates/imly_store_created_admin.html').render(Context({'store':instance})),instance.owner.email,[settings.STORE_EMAIL])
    	msg.content_subtype = "html"
    	msg.send()
    	msg=EmailMessage("Your shop will be reviewed soon!",get_template('email_templates/imly_store_created_owner.html').render(Context({'store':instance})),settings.STORE_EMAIL,[instance.owner.email],bcc=[settings.ADMIN_EMAIL])
    	msg.content_subtype = "html"
    	msg.send()
Beispiel #18
0
def reviewed_mail(sender,instance,created,**kwargs):
	if created:
		site = Site.objects.get(pk=settings.SITE_ID)
		msg = EmailMessage("Reviews",get_template('email_templates/reviews_mail_admin.html').render(Context({'review':instance, 'site': site})),settings.ADMIN_EMAIL,[settings.ADMIN_EMAIL])
		msg.content_subtype = "html"
		msg.send()
		msg = EmailMessage("You just got a review!",get_template('email_templates/reviews_mail_store.html').render(Context({'review':instance, 'site': site})),settings.SIGNUP_EMAIL,[instance.content_object.store.owner.email])
		msg.content_subtype = "html"
		msg.send()
Beispiel #19
0
        def post(self, request, *args, **kwargs):
                form = UserCreationForm(request.POST)
                if form.is_valid():
                        username = form.clean_username()
			user_full_name = form.cleaned_data['first_name']
                        password = form.clean_password2()
                        form.save()
                        user = authenticate(username=username, password=password)
                        login(request, user)
                        userAccount = User_Account(pk=user.pk,user=user,user_full_name=user_full_name)
                        userAccount.save()
			registration_subject = Activity.objects.all()[0].registration_email_subject
			registration_email_from = Activity.objects.all()[0].registration_email_from
                        registration_content = Activity.objects.all()[0].registration_email_message
			activity_content = Activity.objects.all()[0].activity_registration
			activity_to = Activity.objects.all()[0].activity_email
			serverTZ = pytz.timezone(settings.TIME_ZONE)
                	serverToday = serverTZ.localize(datetime.datetime.now())
                        c = {
                        	'username': request.user.first_name.title(),
                                'articles_url': reverse('articles:index'),
                                'consultations_url': reverse('consultations:index'),
                                'professionals_url': reverse('professionals:index'),
                                'categories_url': reverse('categories:index'),
				'contact_url': reverse('home:contactus'),
                                'user_email': request.user.username, 
                                'from_email': registration_email_from,
				'current_date': serverToday
                        }
                        html = registration_content
                        t = Template(html)
                        con = Context(c)
                        message = t.render(con)
			#No need to make a connection
			#connection = get_connection(fail_silently=False,host="mail.gonaturalistic.com",port="465",username="******",password="******",use_tls=True)
			#msg = EmailMessage(registration_subject,message,registration_email_from,[username],connection=connection)
			msg = EmailMessage(registration_subject,message,registration_email_from,[username])
                        msg.content_subtype = "html"
                        msg.send()

			activity_subject = "GoNaturalistic New Member"
                        html = activity_content
                        t = Template(html)
                        con = Context(c)
			activity_message = t.render(con) 
                        msg2 = EmailMessage(activity_subject,activity_message,registration_email_from,[activity_to])
                        msg2.content_subtype = "html"
                        msg2.send()
			
                        if self.request.is_ajax():
                                data = {'user': '******'}
                                return self.render_to_json_response(data)
                else:
                        if self.request.is_ajax():
                                #data = {'user': '******'}
                                return self.render_to_json_response(form.errors)
Beispiel #20
0
def sendPass(request):

	user_email = request.POST['user_email']

	try:

		user = User.objects.get(username__exact = user_email)

		#send email
		email_link = "http://" + domain + "/users/reqPass?email=" + user.email
		
		subject = "dcmdb Password Change Request"
		
		body = ("Greetings " + user.username + "! <br />"
				" It appears someone has requested to reset your password. <br />"
				" Please click the link below to finish the password change process with our website! <br /><br />"
				" <a href='" + email_link + "'>Change Password</a> ")
		
		to_email = user.email

		email = EmailMessage(subject, body, to=[to_email])
		email.content_subtype = "html"

		email.send()

		return HttpResponse('{"success": true, "msg": "Password reset sent to email!"}', content_type="application/json")

	except ObjectDoesNotExist:

		try:
			
			user = User.objects.get(email__exact = user_email)

			#send email
			email_link = "http://" + domain + "/users/reqPass?email=" + user.email
			
			subject = "dcmdb Password Change Request"
			
			body = ("Greetings " + user.username + "! <br />"
					" It appears someone has requested to reset your password. <br />"
					" Please click the link below to finish the password change process with our website! <br /><br />"
					" <a href='" + email_link + "'>Change Password</a> ")
			
			to_email = user.email

			email = EmailMessage(subject, body, to=[to_email])
			email.content_subtype = "html"

			email.send()

			return HttpResponse('{"success": true, "msg": "Password reset sent to email!"}', content_type="application/json")

		except ObjectDoesNotExist:

			return HttpResponse('{"success": false, "msg": "Username or email was not found in our records!"}', 
								content_type="application/json")
Beispiel #21
0
def mail_from_source(announcement):
        mo = announcement.member_organization
        glean = announcement.glean

        from_address = "{name} <{email}>".format(
            name=mo.name,
            email=settings.ANNOUNCEMENT_FROM_EMAIL
        )

        if announcement.title:
            subject = announcement.title
        else:
            subject = glean.title
        count = 0

        if mo.testing:
            for recipient in announcement.email_recipients.all():
                profile = recipient.profile
                body = render_email(announcement, profile)
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)

            if mo.testing_email:
                profile = announcement.glean.created_by.profile
                body = render_email(announcement, profile)
                msg = EmailMessage(
                    subject,
                    body,
                    from_address,
                    [mo.testing_email]
                )
                msg.content_subtype = "html"
                msg.send()
                count += 1

        else:
            for recipient in announcement.email_recipients.all():
                profile = recipient.profile
                body = render_email(announcement, profile)
                msg = EmailMessage(
                    subject,
                    body,
                    from_address,
                    [recipient.email]
                )
                msg.content_subtype = "html"
                msg.send()
                count += 1
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)
            for recipient in announcement.phone_recipients.all():
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)
        glean.save()
        return count
Beispiel #22
0
def mail_from_source(announcement):
        mo = announcement.member_organization
        glean = announcement.glean

        from_address = slugify(
            unicode(mo)
        ) + "@vermontgleaningcollective.org"

        if announcement.title:
            subject = announcement.title
        else:
            subject = glean.title
        count = 0

        if mo.testing:
            for recipient in announcement.email_recipients.all():
                profile = recipient.profile
                body = render_email(announcement, profile)
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)

            if mo.testing_email:
                profile = announcement.glean.created_by.profile
                body = render_email(announcement, profile)
                msg = EmailMessage(
                    subject,
                    body,
                    from_address,
                    [mo.testing_email]
                )
                msg.content_subtype = "html"
                msg.send()
                count += 1

        else:
            for recipient in announcement.email_recipients.all():
                profile = recipient.profile
                body = render_email(announcement, profile)
                msg = EmailMessage(
                    subject,
                    body,
                    from_address,
                    [recipient.email]
                )
                msg.content_subtype = "html"
                msg.send()
                count += 1
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)
            for recipient in announcement.phone_recipients.all():
                if recipient not in glean.invited_volunteers.all():
                    glean.invited_volunteers.add(recipient)
        glean.save()
        return count
Beispiel #23
0
	def handle(self,*args,**options):
		for storeorder in StoreOrder.objects.filter(order__status = Order.IMLY_CONFIRMED,delivered_on__startswith = date.today()):
			product_detail = []
			for orderitem in storeorder.order.items.all():
				if orderitem.product.store == storeorder.store:
					product_detail.append(orderitem)
			msg = EmailMessage("Reminder: Order due today",get_template('email_templates/reminder_delivery_store.html').render(Context({'store':storeorder.store,'product_detail':product_detail,'storeorder':storeorder})),settings.ORDERS_EMAIL,[storeorder.store.owner.email],bcc=[settings.ADMIN_EMAIL])
			msg.content_subtype = "html"
			msg.send()
			msg = EmailMessage("Reminder: Order due today",get_template('email_templates/reminder_delivery_buyer.html').render(Context({'order':storeorder.order,'store':storeorder.store,'store_total':storeorder.store_total})),settings.ORDERS_EMAIL,[storeorder.order.email],bcc=[settings.ADMIN_EMAIL])
			msg.content_subtype = "html"
			msg.send()
Beispiel #24
0
	def form_valid(self, form):
		u = User.objects.create_user(
	        form.cleaned_data['email'],
	        form.cleaned_data['email'],
	        form.cleaned_data['password']
	    )
		u.first_name = form.cleaned_data['first_name']
		u.last_name = form.cleaned_data['last_name']
		u.is_active = False
		u.profile.city = form.cleaned_data['city']
		u.profile.province = form.cleaned_data['province']
		u.profile.save()
		u.save()

		logo = form.cleaned_data['logo']


		conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
		bucket = conn.get_bucket(settings.AWS_BUCKET)
		k = Key(bucket)
		k.key = 'uploads/organization_logo_%s' % str(u.id)
		k.set_contents_from_string(form.cleaned_data['logo'].read())

		o = UserOrganization(user=u)
		o.organization = form.cleaned_data['organization']
		o.website = form.cleaned_data['website']
		o.logo = k.key
		o.save()	

		# Send registration email to user
		template = get_template('emails/organization_register_success.html')
		content = Context({ 'email': form.cleaned_data['email'], 'first_name': form.cleaned_data['first_name'], 'last_name': form.cleaned_data['last_name'] })
		content = template.render(content)

		subject, from_email, to = 'My Effect - Signup Successful', '*****@*****.**', form.cleaned_data['email']

		mail = EmailMessage(subject, content, from_email, [to])
		mail.content_subtype = "html"
		mail.send()

		# Send notification email to administrator
		template = get_template('emails/register_email_notification.html')
		content = Context({ 'email': form.cleaned_data['email'] })
		content = template.render(content)

		subject, from_email, to = 'My Effect - Organization Signup Successful', '*****@*****.**', '*****@*****.**'

		mail = EmailMessage(subject, content, from_email, [to])
		mail.content_subtype = "html"
		# mail.attach(logo.name, logo.read(), logo.content_type)
		mail.send()

		return HttpResponseRedirect('/register-success/')
Beispiel #25
0
def sendMail(mail_type, variables={}, subject=None, mails=None):
    """
    For each type you must create "qshop/mails/{{ mail_type }}.html" template
    You can also create "qshop/mails/{{ mail_type }}_admin.html" template.
    Then if "admin_mails" specified it will be used to send modified copy of mail,
    variables dict will be appended with "body" variable, wich constains mail body

    reply_to_mail (requred)
    mails
    subject
    subject_prefix
    admin_mails
    admin_subject_prefix
    """

    if mail_type not in MAIL_TYPES:
        raise 'No such mail type in list!'

    mailconf = MAIL_TYPES[mail_type]

    if 'SITE_URL' not in variables:
        variables['SITE_URL'] = settings.SITE_URL

    body = render_to_string("qshop/mails/%s.html" % mail_type, variables)

    if not mails:
        if 'mails' in mailconf:
            mails = mailconf['mails']
        else:
            raise 'No mail to send to!'
    elif isinstance(mails, str):
        mails = (mails,)

    if not subject:
        subject = _(mailconf['subject'])

    if 'subject_prefix' in mailconf and mailconf['subject_prefix']:
        subject = "%s%s" % (__(mailconf['subject_prefix']), subject)

    email = EmailMessage(subject, body, mailconf['reply_to_mail'], mails)
    email.content_subtype = "html"
    email.send()

    if 'admin_mails' in mailconf:
        try:
            body = render_to_string("qshop/mails/%s_admin.html" % mail_type, variables.update({'body': body}))
        except TemplateDoesNotExist:
            pass
        if 'admin_subject_prefix' in mailconf:
            subject = "%s%s" % (mailconf['admin_subject_prefix'], subject)
        email = EmailMessage(subject, body, mailconf['reply_to_mail'], mailconf['admin_mails'])
        email.content_subtype = "html"
        email.send()
Beispiel #26
0
def pricing(request):
    ctx = dict(title="Pricing")
    if request.method == 'POST':
        if 'phone' in request.POST:
            subject = "Someone wants to buy subscription for Onekloud CRM!"
            pricing_type = request.POST['pricing'].capitalize()
            body = "User wants to buy pricing '{type}'.".format(
                type=pricing_type)
            data = dict(email=request.POST['email'],
                        phone=request.POST['phone'],
                        body=body)

            html = mark_safe(render_to_string('pages/email.html', data))
            recipients = ('*****@*****.**', '*****@*****.**')
            msg = EmailMessage(subject, html, settings.SUPPORT_EMAIL,
                               recipients)
            msg.content_subtype = 'html'
            msg.send()
            messages.success(
                request, "Thank you! We will contact you very soon.")
        else:
            form = SignupForm(request.POST)
            if form.is_valid():
                # Email settings.
                subject = "Free trial activation for Onekloud CRM"
                data = form.cleaned_data

                # With this hash we will check if passed data is valid.
                key = '{key}{email}{company}'.format(
                    key=settings.ACTIVATION_SALT, email=data['email'],
                    company=data['company']).encode('utf8')
                data['key'] = hashlib.md5(key).hexdigest()

                encdata = urllib.parse.urlencode(data)
                html = mark_safe(
                    render_to_string('pages/activation_email.html',
                                     dict(params=encdata)))
                msg = EmailMessage(
                    subject, html, settings.SUPPORT_EMAIL, [data['email']],
                    headers={'Reply-To': settings.SUPPORT_EMAIL})
                msg.content_subtype = 'html'
                msg.send()
                messages.success(
                    request, "Thank you! We have sent you activation link to "
                             "{email}.".format(email=data['email']))
            else:
                messages.error(request, form.errors)
    else:
        ctx['signup_form'] = SignupForm()
    return render(request, 'pages/pricing.html', ctx)
Beispiel #27
0
def send_email(email_body, email_type=settings.GENERIC,
               recipients=None, site=None, headers=None, **kwargs):
    recipients = recipients or []

    company_name = 'My.jobs'
    domain = 'my.jobs'

    if site:
        domain = site.email_domain
        if site.canonical_company:
            company_name = site.canonical_company.name

    kwargs['company_name'] = company_name
    kwargs['domain'] = domain.lower()

    sender = settings.EMAIL_FORMATS[email_type]['address']
    sender = sender.format(**kwargs)

    # Capitalize domain for display purposes.
    kwargs['domain'] = kwargs['domain'].lower()
    subject = settings.EMAIL_FORMATS[email_type]['subject']
    subject = subject.format(**kwargs)

    email_kwargs = {
        'subject': subject, 'body': email_body, 'from_email': sender,
        'to': recipients
    }
    if headers is not None:
        email_kwargs['headers'] = headers
    message = EmailMessage(**email_kwargs)
    message.content_subtype = 'html'
    message.send()

    return message
Beispiel #28
0
def cdclient_cargo(request, id):
    cdClient = get_object_or_404(CdClient, id=id)
    if request.method == "POST":
        form = CargoForm(request.POST.copy())
        if form.is_valid():
            cargo = form.save(commit=False)
            cargo.cdclient = cdClient
            cargo.save()
            message = loader.get_template("shipit/sent_email.html").render(Context({"cdClient":cdClient,"cargo":cargo}))
            mail = EmailMessage(
                "Pardus DVD isteğiniz",
                message,
                "Özgürlükiçin <%s>" % DEFAULT_FROM_EMAIL,
                [DVD_MAIL_LIST, cdClient.email],
                headers={"Message-ID":"%s-%s" % (cdClient.id, cdClient.hash)}
            )
            mail.content_subtype = "html"
            mail.send(fail_silently=True)
            cdClient.sent = True
            cdClient.save()

            return HttpResponseRedirect(cdClient.get_absoulte_url())
    else:
        form = CargoForm()
    return render_response(request, "shipit/cargo.html", locals())
def notify_about_exception(exception_title):
    """
    If exception is identified as critical - send email to recipients.
    """
    if EXCEPTION_TITLE_WORDS_TO_NOTIFY and EXCEPTION_RECIPIENTS:
        pattern = r'|'.join(EXCEPTION_TITLE_WORDS_TO_NOTIFY)
        search_result = search(pattern, exception_title, I)

        if search_result is not None:
            message_content = (
                "<p>%(body)s</p><p>Server: "
                "<a href='%(protocol)s://%(domain)s'>%(domain)s</a></p>" % (
                    {
                        'body': exception_title,
                        'protocol': settings.SERVER_PROTOCOL,
                        'domain': settings.CURRENT_SERVER_DOMAIN
                    }
                )
            )
            message = EmailMessage(
                "Error Monitor notification",
                message_content,
                settings.EMAIL_HOST_USER,
                EXCEPTION_RECIPIENTS
            )
            message.content_subtype = 'html'
            message.send(fail_silently=True)
Beispiel #30
0
 def request_new_password(self, request):
     email = self.cleaned_data['username']
     try:
         user = EmailUser.objects.get(email=email)
     except:
         raise PermissionDenied
     user.is_active = False
     user.save()
     try:
         tmp = TempUrl.objects.get(email=email)
     except:
         tmp = TempUrl(email=email, first_name=user.first_name, 
                       last_name=user.last_name)
     tmp.hash = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20))
     now = datetime.datetime.utcnow().replace(tzinfo=utc)
     tmp.invited = now
     tmp.created = now
     tmp.used = None
     tmp.save()
     #email...
     p = {'reason':'reset  password', 'service':'Django email username'}
     p['link'] = request.build_absolute_uri(reverse('django_email_user.views.activate_account', kwargs={'hasher': tmp.hash}))
     html = render_to_string('django_email_user/email-invitation.html', p)
     mail = EmailMessage('You have requested a password reset',
             html, '<Django email username>' + settings.EMAIL_HOST_USER,
             [tmp.email])
     mail.content_subtype = "html"
     mail.send()
     return email
Beispiel #31
0
def check_eligible(request):
    if not request.session.get('admin_login'):
        return HttpResponseRedirect("/login/")
    else:
        company = request.POST['company']
        student = request.POST['hidden']
        comp = Company.objects.get(comp_name=company)

        print(student)
        stud = student.split(",")
        stud_arr = []

        for temp in stud:
            if temp != "on":
                user = temp
                studentObj = Resume.objects.get(user=user)
                name = studentObj.name
                branch = studentObj.branch
                studentEligible = StudentsEligible(stud_user=user,
                                                   comp_name=comp.comp_name,
                                                   stud_name=name,
                                                   branch=branch)
                studentEligible.save()
                stud_arr.append(temp)

        print(stud_arr)
        time = str(comp.time)
        date = str(comp.date)
        email_body = """\
    <html>
      <head></head>
      <body>
        <p>Congratulations. You are eligible for %s.</p>
        <p>Please find below the details for the company.</p>
        <table style="border: 1px solid #dddddd;">
            <tr>
                <th style="border: 1px solid #6A6969;">Company Name</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Profile</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">CTC</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Branch</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Eligibility</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Date</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Time</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Venue</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Bond</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
            <tr>
                <th style="border: 1px solid #6A6969;">Instruction</th>
                <td style="border: 1px solid #6A6969;">%s</td>
            </tr>
        </table>
      </body>
    </html>
    """ % (comp.comp_name, comp.comp_name, comp.comp_profile, comp.ctc,
           comp.branch, comp.eligibility, comp.date, comp.time, comp.venue,
           comp.bond, comp.instruction)
        email = EmailMessage('Placement', email_body, '*****@*****.**',
                             stud_arr)
        email.content_subtype = "html"
        email.send()

        msg = {'success': "Company added and mail sent to eligible students."}
        return render(request, 'add_company.html', msg)
Beispiel #32
0
def deploy(app,
           member,
           business_type,
           project_name,
           billing_plan,
           theme,
           monthly_cost,
           invoice_entries,
           billing_cycle,
           domain=None,
           business_category=None,
           bundle=None,
           partner_retailer=None):
    project_name_slug = slugify(
        project_name)  # Eg: slugify('Cool Shop') = 'cool-shop'
    ikwen_name = project_name_slug.replace('-',
                                           '')  # Eg: cool-shop --> 'coolshop'
    pname = ikwen_name
    i = 0
    while True:
        try:
            Service.objects.using(UMBRELLA).get(project_name_slug=pname)
            i += 1
            pname = "%s%d" % (ikwen_name, i)
        except Service.DoesNotExist:
            ikwen_name = pname
            break
    api_signature = generate_random_key(30, alpha_num=True)
    while True:
        try:
            Service.objects.using(UMBRELLA).get(api_signature=api_signature)
            api_signature = generate_random_key(30, alpha_num=True)
        except Service.DoesNotExist:
            break
    database = ikwen_name
    domain = 'go.' + pname + '.ikwen.com'
    domain_type = Service.SUB
    is_naked_domain = False
    url = 'http://go.ikwen.com/' + pname
    if getattr(settings, 'IS_UMBRELLA', False):
        admin_url = url + '/ikwen' + reverse('ikwen:staff_router')
    else:  # This is a deployment performed by a partner retailer
        admin_url = url + reverse('ikwen:staff_router')
    is_pro_version = billing_plan.is_pro_version
    now = datetime.now()
    expiry = now + timedelta(days=15)

    # Create a copy of template application in the Cloud folder
    app_folder = CLOUD_HOME + '000Tpl/AppSkeleton'
    website_home_folder = CLOUD_FOLDER + ikwen_name
    media_root = CLUSTER_MEDIA_ROOT + ikwen_name + '/'
    media_url = CLUSTER_MEDIA_URL + ikwen_name + '/'
    default_images_folder = CLOUD_FOLDER + '000Tpl/images/000Default'
    theme_images_folder = CLOUD_FOLDER + '000Tpl/images/%s/%s' % (
        theme.template.slug, theme.slug)
    if os.path.exists(theme_images_folder):
        if os.path.exists(media_root):
            shutil.rmtree(media_root)
        shutil.copytree(theme_images_folder, media_root)
        logger.debug("Media folder '%s' successfully created from '%s'" %
                     (media_root, theme_images_folder))
    elif os.path.exists(default_images_folder):
        if os.path.exists(media_root):
            shutil.rmtree(media_root)
        shutil.copytree(default_images_folder, media_root)
        logger.debug("Media folder '%s' successfully created from '%s'" %
                     (media_root, default_images_folder))
    elif not os.path.exists(media_root):
        os.makedirs(media_root)
        logger.debug("Media folder '%s' successfully created empty" %
                     media_root)
    favicons_folder = media_root + 'icons'
    if not os.path.exists(favicons_folder):
        os.makedirs(favicons_folder)
    if os.path.exists(website_home_folder):
        shutil.rmtree(website_home_folder)
    shutil.copytree(app_folder, website_home_folder)
    logger.debug("Service folder '%s' successfully created" %
                 website_home_folder)

    can_manage_delivery_options = False
    if business_type == OperatorProfile.PROVIDER:
        settings_template = 'kakocase/cloud_setup/settings.provider.html'
        can_manage_delivery_options = True
    elif business_type == OperatorProfile.RETAILER:
        settings_template = 'kakocase/cloud_setup/settings.retailer.html'
    elif business_type == OperatorProfile.LOGISTICS:
        settings_template = 'kakocase/cloud_setup/settings.delivery.html'
        auth_code = ikwen_name[:4] + now.strftime('%S')
    elif business_type == OperatorProfile.BANK:
        settings_template = 'kakocase/cloud_setup/settings.bank.html'

    service = Service(member=member,
                      app=app,
                      project_name=project_name,
                      project_name_slug=ikwen_name,
                      domain=domain,
                      database=database,
                      url=url,
                      domain_type=domain_type,
                      expiry=expiry,
                      admin_url=admin_url,
                      billing_plan=billing_plan,
                      billing_cycle=billing_cycle,
                      monthly_cost=monthly_cost,
                      version=Service.TRIAL,
                      retailer=partner_retailer,
                      api_signature=api_signature,
                      home_folder=website_home_folder,
                      settings_template=settings_template)
    service.save(using=UMBRELLA)
    logger.debug("Service %s successfully created" % pname)

    if business_type == OperatorProfile.RETAILER:
        # Copy Categories image to local media folder as the Retailer is allowed to change them
        pass

    # Re-create settings.py file as well as apache.conf file for the newly created project
    secret_key = generate_django_secret_key()
    if is_naked_domain:
        allowed_hosts = '"%s", "www.%s"' % (domain, domain)
    else:
        allowed_hosts = '"go.ikwen.com"'
    settings_tpl = get_template(settings_template)
    settings_context = Context({
        'secret_key': secret_key,
        'ikwen_name': ikwen_name,
        'service': service,
        'static_root': STATIC_ROOT,
        'static_url': STATIC_URL,
        'media_root': media_root,
        'media_url': media_url,
        'allowed_hosts': allowed_hosts,
        'debug': getattr(settings, 'DEBUG', False)
    })
    settings_file = website_home_folder + '/conf/settings.py'
    fh = open(settings_file, 'w')
    fh.write(settings_tpl.render(settings_context))
    fh.close()
    logger.debug("Settings file '%s' successfully created" % settings_file)

    # Import template database and set it up
    if business_type == OperatorProfile.BANK:
        db_folder = CLOUD_FOLDER + '000Tpl/DB/CashFlex'
    else:
        db_folder = CLOUD_FOLDER + '000Tpl/DB/000Default'
        theme_db_folder = CLOUD_FOLDER + '000Tpl/DB/%s/%s' % (
            theme.template.slug, theme.slug)
        if os.path.exists(theme_db_folder):
            db_folder = theme_db_folder

    host = getattr(settings, 'DATABASES')['default'].get('HOST', '127.0.0.1')
    subprocess.call(
        ['mongorestore', '--host', host, '-d', database, db_folder])
    logger.debug("Database %s successfully created on host %s from %s" %
                 (database, host, db_folder))

    add_database_to_settings(database)
    for group in Group.objects.using(database).all():
        try:
            gpl = GroupPermissionList.objects.using(database).get(group=group)
            group.delete()
            group.save(using=database
                       )  # Recreate the group in the service DB with a new id.
            gpl.group = group  # And update GroupPermissionList object with the newly re-created group
            gpl.save(using=database)
        except GroupPermissionList.DoesNotExist:
            group.delete()
            group.save(using=database
                       )  # Re-create the group in the service DB with anyway.
    new_sudo_group = Group.objects.using(database).get(name=SUDO)

    for s in member.get_services():
        db = s.database
        add_database_to_settings(db)
        collaborates_on_fk_list = member.collaborates_on_fk_list + [service.id]
        customer_on_fk_list = member.customer_on_fk_list + [service.id]
        group_fk_list = member.group_fk_list + [new_sudo_group.id]
        Member.objects.using(db).filter(pk=member.id).update(
            collaborates_on_fk_list=collaborates_on_fk_list,
            customer_on_fk_list=customer_on_fk_list,
            group_fk_list=group_fk_list)

    member.collaborates_on_fk_list = collaborates_on_fk_list
    member.customer_on_fk_list = customer_on_fk_list
    member.group_fk_list = group_fk_list

    member.is_iao = True
    member.save(using=UMBRELLA)

    member.is_bao = True
    member.is_staff = True
    member.is_superuser = True

    app.save(using=database)
    member.save(using=database)
    logger.debug("Member %s access rights successfully set for service %s" %
                 (member.username, pname))

    from ikwen.billing.mtnmomo.views import MTN_MOMO
    from ikwen.billing.orangemoney.views import ORANGE_MONEY
    # Copy payment means to local database
    for mean in PaymentMean.objects.using(UMBRELLA).all():
        if mean.slug == 'paypal':
            mean.action_url_name = 'shopping:paypal_set_checkout'
        if mean.slug == MTN_MOMO:
            mean.is_main = True
            mean.is_active = True
        elif mean.slug == ORANGE_MONEY:
            mean.is_main = False
            mean.is_active = True
        else:
            mean.is_main = False
            mean.is_active = False
        mean.save(using=database)
        logger.debug("PaymentMean %s created in database: %s" %
                     (mean.slug, database))

    # Copy themes to local database
    for template in Template.objects.using(UMBRELLA).all():
        template.save(using=database)
    for th in Theme.objects.using(UMBRELLA).all():
        th.save(using=database)
    logger.debug("Template and theme successfully bound for service: %s" %
                 pname)

    FlatPage.objects.using(database).get_or_create(
        url=FlatPage.AGREEMENT,
        title=FlatPage.AGREEMENT.capitalize(),
        content=_('Agreement goes here'))
    FlatPage.objects.using(database).get_or_create(
        url=FlatPage.LEGAL_MENTIONS,
        title=FlatPage.LEGAL_MENTIONS.capitalize(),
        content=_('Legal mentions go here'))

    # Add member to SUDO Group
    obj_list, created = UserPermissionList.objects.using(
        database).get_or_create(user=member)
    obj_list.group_fk_list.append(new_sudo_group.id)
    obj_list.save(using=database)
    logger.debug("Member %s successfully added to sudo group for service: %s" %
                 (member.username, pname))

    # Create wallets
    wallet = OperatorWallet.objects.using('wallets').create(
        nonrel_id=service.id, provider=MTN_MOMO)
    OperatorWallet.objects.using('wallets').create(nonrel_id=service.id,
                                                   provider=ORANGE_MONEY)
    mail_signature = "%s<br>" \
                     "<a href='%s'>%s</a>" % (project_name, 'http://' + domain, domain)
    invitation_message = _(
        "Hey $client<br>"
        "We are inviting you to join our awesome community on ikwen.")
    config = OperatorProfile(
        service=service,
        rel_id=wallet.id,
        media_url=media_url,
        ikwen_share_fixed=billing_plan.tx_share_fixed,
        ikwen_share_rate=billing_plan.tx_share_rate,
        can_manage_delivery_options=can_manage_delivery_options,
        business_type=business_type,
        is_pro_version=is_pro_version,
        theme=theme,
        currency_code='XAF',
        currency_symbol='XAF',
        signature=mail_signature,
        max_products=billing_plan.max_objects,
        decimal_precision=0,
        company_name=project_name,
        contact_email=member.email,
        contact_phone=member.phone,
        business_category=business_category,
        bundle=bundle,
        sms_api_script_url=SMS_API_URL,
        invitation_message=invitation_message)
    config.save(using=UMBRELLA)
    base_config = config.get_base_config()
    base_config.save(using=UMBRELLA)
    from daraja.models import DARAJA
    if partner_retailer:
        partner_retailer.save(using=database)
        try:
            if partner_retailer.app.slug == DARAJA:
                partner_db = partner_retailer.database
                add_database_to_settings(partner_db)
                ikwen_service_partner = Service.objects.using(partner_db).get(
                    project_name_slug='ikwen')
                set_counters(ikwen_service_partner)
                increment_history_field(ikwen_service_partner,
                                        'community_history')
        except:
            logger.error(
                "Could not set Followers count upon Service deployment",
                exc_info=True)

    if bundle:  # Tsunami bundle
        from echo.models import Balance
        token = ''.join(
            [random.SystemRandom().choice(string.digits) for i in range(6)])
        expiry = now + timedelta(days=bundle.support_bundle.duration)
        SupportCode.objects.using(UMBRELLA).create(
            service=service,
            bundle=bundle.support_bundle,
            token=token,
            expiry=expiry)
        Balance.objects.using('wallets').create(service_id=service.id)

    service.save(using=database)
    if business_type == OperatorProfile.LOGISTICS:
        config.auth_code = auth_code

    theme.save(using=database
               )  # Causes theme to be routed to the newly created database
    if business_category:
        business_category.save(using=database)
    config.save(using=database)

    InvoicingConfig.objects.using(database).create()
    logger.debug("Configuration successfully added for service: %s" % pname)

    # Copy samples to local database
    for product in Product.objects.using(database).all():
        product.provider = service
        product.save(using=database)
    logger.debug("Sample products successfully copied to database %s" %
                 database)

    # Create delivery options: Pick-up in store and Free home delivery
    DeliveryOption.objects.using(database).create(
        company=service,
        type=DeliveryOption.PICK_UP_IN_STORE,
        name=_("Pick up in store"),
        slug='pick-up-in-store',
        short_description=_("2H after order"),
        cost=0,
        max_delay=2)
    DeliveryOption.objects.using(database).create(
        company=service,
        type=DeliveryOption.HOME_DELIVERY,
        name=_("Home delivery"),
        slug='home-delivery',
        short_description=_("Max. 72H after order"),
        cost=500,
        max_delay=72)

    # Apache Server cloud_setup
    go_apache_tpl = get_template('core/cloud_setup/apache.conf.local.html')
    apache_context = Context({
        'is_naked_domain': is_naked_domain,
        'domain': domain,
        'home_folder': website_home_folder,
        'ikwen_name': ikwen_name
    })
    if is_naked_domain:
        apache_tpl = get_template('kakocase/cloud_setup/apache.conf.html')
        fh = open(website_home_folder + '/apache.conf', 'w')
        fh.write(apache_tpl.render(apache_context))
        fh.close()
    fh = open(website_home_folder + '/go_apache.conf', 'w')
    fh.write(go_apache_tpl.render(apache_context))
    fh.close()

    vhost = '/etc/apache2/sites-enabled/go_ikwen/' + pname + '.conf'
    subprocess.call(
        ['sudo', 'ln', '-sf', website_home_folder + '/go_apache.conf', vhost])
    if is_naked_domain:
        vhost = '/etc/apache2/sites-enabled/' + domain + '.conf'
        subprocess.call(
            ['sudo', 'ln', '-sf', website_home_folder + '/apache.conf', vhost])
    logger.debug("Apache Virtual Host '%s' successfully created" % vhost)

    # Send notification and Invoice to customer
    number = get_next_invoice_number()
    now = datetime.now()
    invoice_total = 0
    for entry in invoice_entries:
        invoice_total += entry.item.amount * entry.quantity
    invoice = Invoice(subscription=service,
                      member=member,
                      amount=invoice_total,
                      number=number,
                      due_date=expiry,
                      last_reminder=now,
                      reminders_sent=1,
                      is_one_off=True,
                      entries=invoice_entries,
                      months_count=billing_plan.setup_months_count)
    invoice.save(using=UMBRELLA)
    vendor = get_service_instance()

    if member != vendor.member:
        add_event(vendor,
                  SERVICE_DEPLOYED,
                  member=member,
                  object_id=invoice.id)
    if partner_retailer and partner_retailer.app.slug != DARAJA:
        partner_profile = PartnerProfile.objects.using(UMBRELLA).get(
            service=partner_retailer)
        try:
            Member.objects.get(pk=member.id)
        except Member.DoesNotExist:
            member.is_iao = False
            member.is_bao = False
            member.is_staff = False
            member.is_superuser = False
            member.save(using='default')
        service.save(using='default')
        config.save(using='default')
        sender = '%s <no-reply@%s>' % (partner_profile.company_name,
                                       partner_retailer.domain)
        sudo_group = Group.objects.get(name=SUDO)
        ikwen_sudo_gp = Group.objects.using(UMBRELLA).get(name=SUDO)
        add_event(vendor,
                  SERVICE_DEPLOYED,
                  group_id=ikwen_sudo_gp.id,
                  object_id=invoice.id)
    elif partner_retailer and partner_retailer.app.slug == DARAJA:
        try:
            dara_member = partner_retailer.member
            dara = Dara.objects.get(member=dara_member)
            dara_earnings = invoice_total * dara.share_rate / 100
            phone = member.phone
            if len(phone) == 9 and not phone.startswith('237'):
                member.phone = '237' + member.phone

            template_name = 'daraja/mails/remind_referrer.html'
            activate(dara_member.language)
            subject = _("Congratulations ! %s CFA is waiting for you." %
                        intcomma(dara_earnings))
            try:
                extra_context = {
                    'referee': member,
                    'amount': dara_earnings,
                    'invoice_total': intcomma(invoice_total),
                    'deployed_service': service,
                    'dara_name': dara_member.full_name
                }
                html_content = get_mail_content(subject,
                                                template_name=template_name,
                                                extra_context=extra_context)
                sender = 'ikwen Daraja <*****@*****.**>'
                msg = EmailMessage(subject, html_content, sender,
                                   [dara_member.email])
                msg.content_subtype = "html"
                Thread(target=lambda m: m.send(), args=(msg, )).start()
            except:
                logger.error(
                    "Failed to notify %s Dara after follower deployed Kakocase website."
                    % dara_member.full_name,
                    exc_info=True)
        except Dara.DoesNotExist:
            logging.error("%s - Customer %s has not been referred" %
                          (service.project_name, member.username))
    else:
        sender = 'ikwen Tsunami <*****@*****.**>'
        sudo_group = Group.objects.using(UMBRELLA).get(name=SUDO)
    add_event(vendor,
              SERVICE_DEPLOYED,
              group_id=sudo_group.id,
              object_id=invoice.id)
    invoice_url = 'http://www.ikwen.com' + reverse('billing:invoice_detail',
                                                   args=(invoice.id, ))
    activate(member.language)
    subject = _("Your website %s was created" % project_name)
    html_content = get_mail_content(
        subject,
        template_name='core/mails/service_deployed.html',
        extra_context={
            'service_activated': service,
            'invoice': invoice,
            'member': member,
            'invoice_url': invoice_url
        })
    msg = EmailMessage(subject, html_content, sender, [member.email])
    bcc = ['*****@*****.**', '*****@*****.**']
    if vendor.config.contact_email:
        bcc.append(vendor.config.contact_email)
    msg.bcc = list(set(bcc))
    msg.content_subtype = "html"
    Thread(target=lambda m: m.send(), args=(msg, )).start()
    logger.debug("Notice email submitted to %s" % member.email)
    Thread(target=reload_server).start()
    logger.debug("Apache Scheduled to reload in 5s")
    return service
Beispiel #33
0
def submit_order(request):
    json_request = json.loads(request.body)
    trades = json_request.get('trades')
    cash = json_request.get('cash')
    reasoning = json_request.get('reasoning')
    notes = json_request.get('notes')

    if trades is None or cash is None:
        return HttpResponseBadRequest('Error: missing trade information')

    group = get_group(request)
    if isinstance(group, HttpResponseForbidden):
        return group

    if DEBUG != 'True':
        keen.add_events({
            'trades':
            trades,
            'orders': [{
                'group': group.get('group_account'),
                'email': request.user.email
            }]
        })

    try:
        sender = '%s %s <%s>' % (request.user.first_name,
                                 request.user.last_name, request.user.email)
        other_members = group.get('members').exclude(email=request.user.email)
        other_members_emails = [
            '%s %s <%s>' % (member.first_name, member.last_name, member.email)
            for member in other_members
        ]

        supervisors = [
            '%s %s <%s>' %
            (supervisor.first_name, supervisor.last_name, supervisor.email)
            for supervisor in group.get('supervisors')
        ]

        trader_content = render_to_string(
            'trade/email_template.html', {
                'trades': trades,
                'cash': cash,
                'notes': notes,
                'group_account': group.get('group_account'),
                'group_number': group.get('group_number')
            }, request)

        supervisor_content = render_to_string(
            'trade/email_template.html', {
                'trades': trades,
                'cash': cash,
                'reasoning': reasoning,
                'notes': notes,
                'group_account': group.get('group_account'),
                'group_number': group.get('group_number')
            }, request)
        from aitrading.templatetags.template_tags import remove_extra_0
        trader_msg = EmailMessage(
            from_email=sender,
            to=supervisors,
            bcc=[sender],
            cc=other_members_emails,
            subject='Applied Investments Trade Request - Group %s (%s)' %
            (group.get('group_number'),
             remove_extra_0(group.get('group_account'))),
            body=str(trader_content))
        trader_msg.content_subtype = 'html'
        trader_msg.send()

        supervisor_msg = EmailMessage(
            from_email=sender,
            to=supervisors,
            bcc=[sender],
            cc=other_members_emails,
            subject=
            'Reasoning for Applied Investments Trade Request - Group %s (%s)' %
            (group.get('group_number'),
             remove_extra_0(group.get('group_account'))),
            body=str(supervisor_content))
        supervisor_msg.content_subtype = 'html'
        supervisor_msg.send()

        return JsonResponse(data={})

    except Exception as e:
        return HttpResponse('Error: ' + str(e), status=500)
Beispiel #34
0
def sendHtmlEmail(to,
                  subject,
                  context,
                  template,
                  cc,
                  bcc,
                  from_email,
                  attachment1=None):

    email_delivery = env('EMAIL_DELIVERY', 'off')
    override_email = env('OVERRIDE_EMAIL', None)
    email_instance = env('EMAIL_INSTANCE', 'DEV')

    context['default_url'] = env('DEFAULT_URL', '')
    context['default_url_internal'] = env('DEFAULT_URL_INTERNAL', '')
    log_hash = int(
        hashlib.sha1(str(datetime.datetime.now()).encode('utf-8')).hexdigest(),
        16) % (10**8)
    if email_delivery != 'on':
        print("EMAIL DELIVERY IS OFF NO EMAIL SENT -- applications/email.py ")
        return False

    if template is None:
        raise ValidationError('Invalid Template')
    if to is None:
        raise ValidationError('Invalid Email')
    if subject is None:
        raise ValidationError('Invalid Subject')

    if from_email is None:
        if settings.DEFAULT_FROM_EMAIL:
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_email = '*****@*****.**'

    context['version'] = settings.APPLICATION_VERSION_NO
    # Custom Email Body Template
    context['body'] = get_template(template).render(context)
    # Main Email Template Style ( body template is populated in the center
    main_template = get_template('email-dpaw-template.html').render(context)

    if override_email is not None:
        to = override_email.split(",")
        if cc:
            cc = override_email.split(",")
        if bcc:
            bcc = override_email.split(",")

    if len(to) > 1:
        for to_email in to:
            msg = EmailMessage(subject,
                               main_template,
                               to=[to_email],
                               cc=cc,
                               from_email=from_email,
                               headers={'System-Environment': email_instance})
            msg.content_subtype = 'html'
            if attachment1:
                msg.attach_file(attachment1)

            #msg.send()

            try:
                email_log(str(log_hash) + ' ' + subject)
                msg.send()
                email_log(str(log_hash) + ' Successfully sent to mail gateway')
            except Exception as e:
                email_log(str(log_hash) + ' Error Sending - ' + str(e))

            #print ("MESSGE")
            #print (str(msg.message()))
    else:
        msg = EmailMessage(subject,
                           main_template,
                           to=to,
                           cc=cc,
                           from_email=from_email,
                           headers={'System-Environment': email_instance})
        msg.content_subtype = 'html'
        if attachment1:
            msg.attach_file(attachment1)
        #msg.send()
        #print ("MESSGE")
        #print (str(msg.message()))

        try:
            email_log(str(log_hash) + ' ' + subject)
            msg.send()
            email_log(str(log_hash) + ' Successfully sent to mail gateway')
        except Exception as e:
            email_log(str(log_hash) + ' Error Sending - ' + str(e))

    if 'app' in context:
        eml_content = msg.message().as_bytes()
        #file_name = settings.BASE_DIR+"/private-media/tmp/"+str(log_hash)+".msg"
        #with open(file_name, "wb") as outfile:
        #   outfile.write(eml_content)

        #f = open(file_name, "r")
        #       print(f.read())
        print("CLASS")
        print(":" + context['app'].__class__.__name__ + ":")
        if context['app'].__class__.__name__ == 'Compliance':
            print("LOADING")
            doc = models.Record()
            doc.upload.save(str(log_hash) + '.eml',
                            ContentFile(eml_content),
                            save=False)
            doc.name = str(log_hash) + '.eml'
            doc.file_group = 2007
            doc.file_group_ref_id = context['app'].id
            doc.extension = '.eml'
            doc.save()

            approval = approval_models.Approval.objects.get(
                id=context['app'].approval_id)
            comms = approval_models.CommunicationApproval.objects.create(
                approval=approval,
                comms_type=2,
                comms_to=str(to),
                comms_from=from_email,
                subject=subject,
                details='see attachment')
            comms.records.add(doc)
            comms.save()
        elif context['app'].__class__.__name__ == 'Approval':
            doc = models.Record()
            doc.upload.save(str(log_hash) + '.eml',
                            ContentFile(eml_content),
                            save=False)
            doc.name = str(log_hash) + '.eml'
            doc.file_group = 2007
            doc.file_group_ref_id = context['app'].id
            doc.extension = '.eml'
            doc.save()

            comms = approval_models.CommunicationApproval.objects.create(
                approval=context['app'],
                comms_type=2,
                comms_to=str(to),
                comms_from=from_email,
                subject=subject,
                details='see attachment')
            comms.records.add(doc)
            comms.save()
        else:
            doc = models.Record()
            doc.upload.save(str(log_hash) + '.eml',
                            ContentFile(eml_content),
                            save=False)
            doc.name = str(log_hash) + '.eml'
            doc.file_group = 2003
            doc.file_group_ref_id = context['app'].id
            doc.extension = '.eml'
            doc.save()

            comms = models.Communication.objects.create(
                application=context['app'],
                comms_type=2,
                comms_to=str(to),
                comms_from=from_email,
                subject=subject,
                details='see attachment')
            comms.records.add(doc)
            comms.save()
    return True
Beispiel #35
0
        to = [to]

    if template and body and not context:
        context = {"body": body}

    if template and context:
        if type(context) is dict:
            context['settings'] = settings
        body = render_to_string(template, context)
        body = inline_css(body)

    msg = EmailMessage(subject=subject,
                       body=body,
                       from_email=from_email,
                       to=to)
    msg.content_subtype = "html"
    for a in attachments:
        if type(a) in [str, unicode]:
            msg.attach_file(a)
        else:
            msg.attach(a.name, a.data, a.mimetype)

    if async:
        t = threading.Thread(target=async_send, args=[msg])
        t.start()
    else:
        msg.send(fail_silently=fail_silently)


def sendToSupport(subject,
                  body=None,
Beispiel #36
0
def new_order(request):
    email_autofill = request.user.email
    form = OrderForm(initial={'email': email_autofill})
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            editable = form.save(commit=False)
            editable.date = datetime.now()
            editable.save()

            # Send an email to the user with the token:
            surname_headline = form.cleaned_data.get('surname')
            name_headline = surname_headline + ' ' + form.cleaned_data.get(
                'name')
            father_headline = name_headline + ' ' + form.cleaned_data.get(
                'father')
            mail_subject = 'Подтверждение справки для ' + father_headline
            current_site = get_current_site(request)
            token = email_token.make_token(request.user)
            message = render_to_string(
                'order/confirm_order.html', {
                    'surname': form.cleaned_data.get('surname'),
                    'name': form.cleaned_data.get('name'),
                    'father': form.cleaned_data.get('father'),
                    'class_letter': form.cleaned_data.get('class_letter'),
                    'domain': current_site,
                    'token': token,
                    'user_email': form.cleaned_data.get('email'),
                })

            # getting school email and name in English by its name from ChoiceField
            current_school = form.cleaned_data.get('schools')

            to_email_queryset = Schools.objects.filter(
                name=current_school).values('email').get()
            to_email_queryset_string = str(to_email_queryset)
            to_email_string = to_email_queryset_string[
                to_email_queryset_string.find(':') +
                3:to_email_queryset_string.rfind('}') - 1]

            english_name_queryset = Schools.objects.filter(
                name=current_school).values('name_in_english').get()
            english_name_queryset_string = str(english_name_queryset)
            english_name_string = english_name_queryset_string[
                english_name_queryset_string.find(':') +
                3:english_name_queryset_string.rfind('}') - 1]

            # sending confirmation email to school secretary

            email = EmailMessage(mail_subject, message, to=[to_email_string])
            email.content_subtype = "html"
            email.send()

            # creating document for current request and saving it locally

            template_path = settings.MEDIA_ROOT + '\doc_template\school_' + english_name_string + '.docx'
            doc = DocxTemplate(template_path)
            number_of_document = str(editable.pk).zfill(7)
            context = {
                'number': number_of_document,
                'surname': form.cleaned_data.get('surname'),
                'name': form.cleaned_data.get('name'),
                'father': form.cleaned_data.get('father'),
                'class': form.cleaned_data.get('class_letter'),
                'date': datetime.today().strftime("%d.%m.%Y")
            }
            doc.render(context)
            name = settings.MEDIA_ROOT + '\generated_docx\generated_doc_' + str(
                token) + '.docx'
            doc.save(name)

            # convert docx to pdf

            # in_file = settings.MEDIA_ROOT + '\generated_docx\generated_doc_' + str(token)
            # out_file = settings.MEDIA_ROOT + '\generated_docx\generated_doc_' + str(token) + '1'
            #
            # word = comtypes.client.CreateObject('Word.Application')
            # docx = word.Documents.Open(in_file)
            # docx.SaveAs(out_file, FileFormat=17)
            # docx.Close()
            # word.Quit()

            form.save()
            messages.success(request,
                             'Заявка отправлена на рассмотрение секртарю!')
            return redirect('homepage')
    return render(request, 'order/new_order.html', {'form': form})
Beispiel #37
0
def send_mail_address(subject, msg_html, from_address, to_address):
    email = EmailMessage(subject, msg_html, from_address, to_address)
    email.content_subtype = "html"
    email.send()
    return True
Beispiel #38
0
    def save_formset(self, request, form, formset, change):
        fill = [0] * len_inter
        if formset.model not in [
                interview, appointment, offer_ready, offer_approval, in_service
        ]:
            return super(base_infoAdmin,
                         self).save_formset(request, form, formset, change)
        if formset.model not in [appointment, interview, in_service]:
            instances = formset.save(commit=False)
            for instance in instances:
                if not instance.pk:
                    instance.cuser = request.user
                instance.save()
        elif formset.model == interview:
            instances = formset.save(commit=False)
            for instance in instances:
                if not instance.pk:
                    #更新base_info模型后两个字段
                    base_info_instance = base_info.objects.get(
                        pk=instance.inter_user.id)
                    base_info_instance.stage = instance.inter_cho
                    base_info_instance.status = '2'
                    base_info_instance.save()
                    instance.cuser = request.user
                    instance.position = str(
                        instance.inter_user.provience_applied) + str(
                            instance.inter_user.position)
                    i = 0
                    for req_t in req:
                        if instance.point.id in req_t:
                            fill[i] += 1
                        i += 1
                instance.save()
            for ii in range(0, len_inter):
                if fill[ii] and fill[ii] < len(req[ii]):
                    self.message_user(request,
                                      '%s的必填面试要点缺失,请检查!' % inte_mcho[ii],
                                      level=messages.ERROR)
        elif formset.model == in_service:
            instances = formset.save(commit=False)
            for instance in instances:
                instance.cuser = request.user
                if instance.on_board:
                    in_service_instance = base_info.objects.get(
                        pk=instance.offer_user.id)
                    in_service_instance.status = '6'
                    in_service_instance.save()
                else:
                    in_service_instance = base_info.objects.get(
                        pk=instance.offer_user.id)
                    in_service_instance.status = '7'
                    in_service_instance.save()
                instance.save()
        else:
            instances = formset.save(commit=False)
            for instance in instances:
                if not instance.pk:
                    base_info_instance = base_info.objects.get(
                        pk=instance.app_user.id)
                    base_info_instance.stage = instance.inte_cho
                    base_info_instance.status = '1'
                    base_info_instance.save()
                    instance.cuser = request.user
                    try:
                        mailtempalte = mail_template.objects.get(
                            pos_cat=instance.app_user.position.category)
                        mail_message = mailtempalte.template_context.replace(
                            '{姓名}', str(instance.app_user.name)).replace(
                                '{面试类型}', str(instance.inte_cho.name)).replace(
                                    '{时间}',
                                    instance.app_date.strftime(
                                        "%Y-%m-%d %H:%M")
                                ).replace('{地址}', str(
                                    instance.contact.address)).replace(
                                        '{联系人}',
                                        str(instance.contact.contact_person)
                                    ).replace(
                                        '{电话}',
                                        str(instance.contact.contact_phone))
                        msg = EmailMessage('中公教育面试邀请', mail_message,
                                           settings.DEFAULT_FROM_EMAIL,
                                           [request.user.email])
                        msg.content_subtype = 'html'
                        msg.send()
                        self.message_user(
                            request,
                            '%s的系统邮件发送成功!' % str(instance.app_user.name))
                    except:
                        self.message_user(request,
                                          '系统邮件发送失败,请手动发送!',
                                          level=messages.ERROR)
                instance.save()

        formset.save_m2m()
Beispiel #39
0
def send_email_user_mentions(comment_id,
                             called_from,
                             domain="demo.django-crm.io",
                             protocol="http"):
    """ Send Mail To Mentioned Users In The Comment """
    comment = Comment.objects.filter(id=comment_id).first()
    if comment:
        comment_text = comment.comment
        comment_text_list = comment_text.split()
        recipients = []
        for comment_text in comment_text_list:
            if comment_text.startswith("@"):
                if comment_text.strip("@").strip(",") not in recipients:
                    if User.objects.filter(
                            username=comment_text.strip("@").strip(","),
                            is_active=True).exists():
                        email = (User.objects.filter(
                            username=comment_text.strip("@").strip(
                                ",")).first().email)
                        recipients.append(email)

        context = {}
        context["commented_by"] = comment.commented_by
        context["comment_description"] = comment.comment
        if called_from == "accounts":
            context["url"] = (
                protocol + "://" + domain +
                reverse("accounts:view_account", args=(comment.account.id, )))
            subject = "New comment on Account. "
        elif called_from == "contacts":
            context["url"] = (
                protocol + "://" + domain +
                reverse("contacts:view_contact", args=(comment.contact.id, )))
            subject = "New comment on Contact. "
        elif called_from == "leads":
            context["url"] = (
                protocol + "://" + domain +
                reverse("leads:view_lead", args=(comment.lead.id, )))
            subject = "New comment on Lead. "
        elif called_from == "opportunity":
            context["url"] = (protocol + "://" + domain + reverse(
                "opportunity:opp_view", args=(comment.opportunity.id, )))
            subject = "New comment on Opportunity. "
        elif called_from == "cases":
            context["url"] = (
                protocol + "://" + domain +
                reverse("cases:view_case", args=(comment.case.id, )))
            subject = "New comment on Case. "
        elif called_from == "tasks":
            context["url"] = (
                protocol + "://" + domain +
                reverse("tasks:task_detail", args=(comment.task.id, )))
            subject = "New comment on Task. "
        elif called_from == "invoices":
            context["url"] = (protocol + "://" + domain + reverse(
                "invoices:invoice_details", args=(comment.invoice.id, )))
            subject = "New comment on Invoice. "
        elif called_from == "events":
            context["url"] = (
                protocol + "://" + domain +
                reverse("events:detail_view", args=(comment.event.id, )))
            subject = "New comment on Event. "
        else:
            context["url"] = ""
        # subject = 'Django CRM : comment '
        blocked_domains = BlockedDomain.objects.values_list("domain",
                                                            flat=True)
        blocked_emails = BlockedEmail.objects.values_list("email", flat=True)
        if recipients:
            for recipient in recipients:
                if (recipient
                        not in blocked_emails) and (recipient.split("@")[-1]
                                                    not in blocked_domains):
                    recipients_list = [
                        recipient,
                    ]
                    context["mentioned_user"] = recipient
                    html_content = render_to_string("comment_email.html",
                                                    context=context)
                    msg = EmailMessage(
                        subject,
                        html_content,
                        from_email=comment.commented_by.email,
                        to=recipients_list,
                    )
                    msg.content_subtype = "html"
                    msg.send()
Beispiel #40
0
def create_edit(request):
    request_data = json.loads(request.body)

    pk = request_data.get('id', '')
    role = get_role(request.user)
    send_email = request_data.get('send_email', False)
    reminder = request_data.get('reminder', None)
    by = request_data.get('by', None)
    timezone = request_data.get('timezone', None)
    start = request_data.get('start', '')
    end = request_data.get('end', '')
    title = request_data.get('title', '')
    user_ids = request_data.get('user_ids', [])
    market_ids = request_data.get('market_ids', [])
    description = request_data.get('description', '')
    color = request_data.get('color', '')

    ids_to_create = []

    if pk:
        event = Event.objects.get(pk=pk)
        is_owner = request.user == event.user
    else:
        event = Event()
        event.user = request.user
        is_owner = True

    if is_owner:
        # can delete this property?
        has_change = False
        event.all_day = False
        event.title = title
        event.description = description

        if color and role in ['corporate', 'admin', 'finance']:
            event.color = color

        if start:
            new_start = unaware_to_utc(
                datetime.strptime(start, "%Y-%m-%dT%H:%M:%S.%fZ"))
            if not new_start == event.start:
                has_change = True
            event.start = new_start

        if end:
            new_end = unaware_to_utc(
                datetime.strptime(end, "%Y-%m-%dT%H:%M:%S.%fZ"))
            if not new_end == event.end:
                has_change = True
            event.end = new_end

        if role in ['coordinator', 'admin', 'corporate', 'finance']:
            visibility = int(request_data['visibility'])

            if pk and ((event.visibility == 5 and not visibility == 5) or
                       (visibility == 5 and len(market_ids) == 0)):
                event.markets.clear()

            # only request user and should see anywhere
            if visibility == 2:
                event.is_private = True
                if pk and not (event.visibility == visibility):
                    EventUsers.objects.exclude(user=request.user).filter(
                        event=event).delete()
            # all users
            elif visibility == 4:
                event.is_private = False

            # specify characters and markets
            elif visibility == 5:
                if pk:
                    existing_ids = EventUsers.objects.filter(
                        event=event).values_list('user_id', flat=True)

                    ids_to_create = [
                        i for i in user_ids if i not in existing_ids
                    ]
                    ids_to_delete = [
                        i for i in existing_ids
                        if i not in user_ids and not i == request.user.pk
                    ]

                    EventUsers.objects.filter(
                        event=event, user_id__in=ids_to_delete).delete()
                else:
                    ids_to_create = user_ids

            event.visibility = visibility

        else:
            event.visibility = 2

        event.save()

        if event.visibility == 5 and len(market_ids) > 0:
            event.markets.set(market_ids)

        if has_change and pk:
            EventUsers.objects.filter(event=event).update(sent=False)

        if event.visibility == 5 and len(ids_to_create) > 0:
            entities_to_create = []
            for user_id in ids_to_create:
                entities_to_create.append(
                    EventUsers(event=event, user_id=user_id))

            EventUsers.objects.bulk_create(entities_to_create)

    event_users, created = EventUsers.objects.get_or_create(user=request.user,
                                                            event=event)

    if by and reminder:
        offset = get_reminder_minutes_offset(reminder)
        event_users.sending_date = event.start - dt.timedelta(minutes=offset)
        event_users.timezone = timezone
        event_users.by = by
        event_users.reminder = reminder
        event_users.save()

    if not pk and event.visibility in [4, 5] and send_email:
        query_set = User.objects.prefetch_related(
            'groups', 'consultantprofile', 'consultantprofile__market',
            'consultantprofile__supervisor', 'person').acs_users()

        if event.visibility == 5:
            conditions = []
            q_objects = Q()
            if len(market_ids) > 0:
                conditions.append(
                    Q(consultantprofile__market__pk__in=market_ids))

            if len(ids_to_create) > 0:
                conditions.append(Q(pk__in=ids_to_create))

            for condition in conditions:
                q_objects |= condition

            if len(conditions) > 0:
                query_set = query_set.filter(q_objects)

        mails = query_set.values_list('person__email', flat=True)

        if len(mails) > 0:
            event_start_aware = utc_to_timezone_or_default(
                event.start, timezone)

            context = {
                'by': request.user,
                'event': event,
                'event_start_date': event_start_aware.strftime('%b %d, %Y'),
                'event_start_time': event_start_aware.strftime('%I:%M %p'),
                'timezone': timezone
            }

            email = EmailMessage('New event invitation in your ACS dashboard',
                                 render_to_string(
                                     'events/emails/new_event.html', context),
                                 bcc=mails)
            email.content_subtype = 'html'
            email.send()

    # TODO implement serializer
    response = {
        'id':
        event.id,
        'title':
        event.title,
        'start':
        event.start.isoformat() if event.start else '',
        'end':
        event.end.isoformat() if event.end else '',
        'description':
        event.description,
        'url':
        event.url,
        'allDay':
        event.all_day,
        'userId':
        int(0 if event.user is None else event.user_id),
        'visibility':
        event.visibility,
        'imageUrl': (event.image.url
                     if event.image and hasattr(event.image, 'url') else ''),
        'reminderId':
        event.reminder_id if event.reminder_id else '',
        'eventuser': {
            'by': event_users.by,
            'reminder': event_users.reminder
        }
    }

    return JsonResponse(response)
Beispiel #41
0
def change(request):
    if request.GET.get("Command") == "LoadBooking":
        DataString = ""
        merop = request.GET.get("merop")
        email = request.GET.get("email")
        zap = Booking.objects.in_bulk()

        print(merop, email)

        obj_merop = Merop.objects.get(pk=merop)

        for id in zap:
            if zap[id].email == email and zap[id].mero == obj_merop:
                DataString += zap[id].places + ","
        return HttpResponse(DataString)

    if request.GET.get("Command") == "CancelBooking":
        booked = request.GET.get("DataString")
        booked = str(booked).split(',')
        if booked == "":
            return HttpResponse('ошибка')

        email = request.GET.get("email")
        merop = request.GET.get("mero")

        obj_merop = Merop.objects.get(pk=merop)

        data = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Demystifying Email Design</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<body>
	<style>
	* {box-sizing: border-box;}
	body {background: #FFF2E3;}
	.wedding {
	  position: relative;
	  max-width: 350px;
	  margin: 50px auto 0;
	  text-align: center;
	}
	.form-inner:before {
	  display: inline-block;
	  margin-top: -45px;
	  content: url(https://html5book.ru/wp-content/uploads/2017/05/form-flower.png);
	}
	.form-inner {
	  padding: 0 40px 10px;
	  margin-top: 45px;
	  background: #ffffff;
	  border-radius: 2px;
	  box-shadow: 0 0 6px 1px rgba(0,0,0,.1);
	}
	.form-inner h2 {
	  font-weight: 300;
	  font-size: 20px;
	  text-transform: uppercase;
	  font-family: 'Cormorant Garamond', serif;
	}
	.form-content {
	  position: relative;
	  margin: 30px -40px 0 -40px;
	  padding: 10px 40px 0 40px;
	  background: #FFF8F3;
	}
	.form-content:before {
	  content: "";
	  position: absolute;
	  top: -4px;
	  right: 0;
	  left: 0;
	  height: 2px;
	  border-top: 1px solid #DDDDDD;
	  border-bottom: 1px solid #DDDDDD;
	}
	.form-content h3 {
	  font-family: 'Marck Script', cursive;
	  font-size: 22px;
	  color: #898989;
	  font-weight: normal;
	}
	.form-content input,
	.form-content select {
	  height: 38px;
	  line-height: 38px;
	  padding: 0 10px;
	  background: #ffffff;
	  border: 1px solid #DDDDDD;
	  font-size: 20px;
	  font-family: 'Cormorant Garamond', serif;
	  color: #808080;
	  outline: none;
	}
	.form-content input {width: 100%;}
	.form-content input:focus,
	.form-content select:focus {border-color: #C44D58;}
	.form-content input[type="submit"] {
	  margin: 20px 0;
	  padding: 0 10px;
	  background: #FF6B6B;
	  color: #ffffff;   
	  font-size: 18px;
	  text-transform: uppercase;
	  border-width: 0;
	  border-radius: 20px;
	  cursor: pointer;
	  transition: .2s linear}
	.form-content input[type="submit"]:hover {background: #C44D58;}
	</style>
	<form class="wedding">
	  <div class="form-inner">
		<h2>Вы успешно отменили бронирование<br><h2>
		</div>
	  </div>
	</form>
	</body>
	</head>
</html>'''

    email1 = EmailMessage('Отмена Бронирования', data, to=[str(email)])
    email1.content_subtype = "html"
    email1.send()

    for i in booked:
        Booking.objects.filter(places=i, mero=obj_merop).delete()
    return HttpResponse("успех")
Beispiel #42
0
def query(request):
    if request.GET.get("Command") == "ConfirmBooking":
        if request.GET.get("password") == "хуй":
            email = request.GET.get("email")
            name = request.GET.get("name")
            merop = request.GET.get("mero")
            place = request.GET.get("place")

            obj_merop = Merop.objects.get(pk=merop)

            Booking.objects.filter(mero=obj_merop,
                                   places=place,
                                   email=email,
                                   username=name).update(conf=1)
            return HttpResponse("каеф")
        else:
            return HttpResponse("ошибка")
    if request.GET.get("Command") == "LoadBooking":
        DataString = ""
        merop = request.GET.get("merop")

        obj_merop = Merop.objects.get(pk=merop)

        zap = Booking.objects.in_bulk()
        for id in zap:
            if zap[id].mero == obj_merop:
                DataString += zap[id].places + ","
        return HttpResponse(DataString)

    if request.GET.get("Command") == "Filler":
        merop = request.GET.get("merop")
        Fill = Merop(mero=merop)
        Fill.save()
        return HttpResponse('good')

    if request.GET.get("Command") == "SaveBooking":
        booked = request.GET.get("DataString")
        booked = str(booked).split(',')
        place = request.GET.get("place")
        date = request.GET.get("date")

        ################################
        #Booking.objects.all().delete()#
        ################################

        email = request.GET.get("email")
        name = request.GET.get("name")
        merop = request.GET.get("mero")

        print(email, name, merop)

        obj_merop = Merop.objects.get(pk=merop)

        #проверка на 5 мест
        k = 0
        prov = Booking.objects.in_bulk()
        for id in prov:
            if prov[id].email == email and prov[id].mero == obj_merop:
                k += 1
                if k >= 2:
                    return HttpResponse("места")

        for i in booked:
            if Booking.objects.filter(places=i, mero=obj_merop).count() != 0:
                return HttpResponse("ошибка")

        for i in booked:
            book = Booking(username=name,
                           email=email,
                           places=i,
                           mero=obj_merop)
            book.save()

        zap = Booking.objects.in_bulk()

        link = "http://127.0.0.1:8000/cancel/?email=" + Crypto(
            email) + "&" + "merop=" + Crypto(
                merop) + "&" + "date=" + date + "&" + "place=" + place

        data = '''
	<!DOCTYPE html>
		<html xmlns="http://www.w3.org/1999/xhtml">
		<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
		<meta content="width=device-width" name="viewport">

		<style>body {
		width: 100% !important; min-width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0;
		}
		.ExternalClass {
		width: 100%;
		}
		.ExternalClass {
		line-height: 100%;
		}
		#backgroundTable {
		margin: 0; padding: 0; width: 100% !important; line-height: 100% !important;
		}
		img {
		outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; max-width: 100%; float: left; clear: both; display: block;
		}
		body {
		background-color: #ffffff; background-repeat: repeat; background-position: center top;
		}
		body {
		color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; padding: 0; margin: 0; text-align: left; line-height: 1.3;
		}
		a:hover {
		color: #2795b6;
		}
		a:active {
		color: #2795b6;
		}
		a:visited {
		color: #2ba6cb;
		}
		h1 a:active {
		color: #2ba6cb !important;
		}
		h2 a:active {
		color: #2ba6cb !important;
		}
		h3 a:active {
		color: #2ba6cb !important;
		}
		h4 a:active {
		color: #2ba6cb !important;
		}
		h5 a:active {
		color: #2ba6cb !important;
		}
		h6 a:active {
		color: #2ba6cb !important;
		}
		h1 a:visited {
		color: #2ba6cb !important;
		}
		h2 a:visited {
		color: #2ba6cb !important;
		}
		h3 a:visited {
		color: #2ba6cb !important;
		}
		h4 a:visited {
		color: #2ba6cb !important;
		}
		h5 a:visited {
		color: #2ba6cb !important;
		}
		h6 a:visited {
		color: #2ba6cb !important;
		}
		table.secondary:hover td {
		background: #d0d0d0 !important; color: #555555;
		}
		table.secondary:hover td a {
		color: #555555 !important;
		}
		table.secondary td a:visited {
		color: #555555 !important;
		}
		table.secondary:active td a {
		color: #555555 !important;
		}
		table.success:hover td {
		background: #457a1a !important;
		}
		table.alert:hover td {
		background: #970b0e !important;
		}
		body.outlook p {
		display: inline !important;
		}
		@media only screen and (min-width: 768px) {
		  table.container {
			width: 580px !important;
		  }
		}
		@media only screen and (max-width: 600px) {
		  .mail img {
			max-width: 100% !important; max-height: 100% !important; padding: 0 !important; width: auto !important; height: auto !important;
		  }
		  .mail .social img {
			width: inherit !important;
		  }
		  .mail img.normal {
			width: inherit !important;
		  }
		  .mail center {
			min-width: 0 !important;
		  }
		  .mail .container {
			width: 100% !important;
		  }
		  .mail .row {
			width: 100% !important; display: block !important;
		  }
		  .mail .wrapper {
			display: block !important; padding-right: 0 !important;
		  }
		  .mail .columns {
			table-layout: fixed !important; float: none !important; width: 100% !important; padding-right: 0px !important; padding-left: 0px !important; display: block !important;
		  }
		  .mail .column {
			table-layout: fixed !important; float: none !important; width: 100% !important; padding-right: 0px !important; padding-left: 0px !important; display: block !important;
		  }
		  .mail .wrapper.first .columns {
			display: table !important;
		  }
		  .mail .wrapper.first .column {
			display: table !important;
		  }
		  .mail table.columns > tbody > tr > td {
			width: 100% !important;
		  }
		  .mail table.column > tbody > tr > td {
			width: 100% !important;
		  }
		  .mail .columns td.one {
			width: 8.33333% !important;
		  }
		  .mail .column td.one {
			width: 8.33333% !important;
		  }
		  .mail .columns td.two {
			width: 16.66667% !important;
		  }
		  .mail .column td.two {
			width: 16.66667% !important;
		  }
		  .mail .columns td.three {
			width: 25% !important;
		  }
		  .mail .column td.three {
			width: 25% !important;
		  }
		  .mail .columns td.four {
			width: 33.33333% !important;
		  }
		  .mail .column td.four {
			width: 33.33333% !important;
		  }
		  .mail .columns td.five {
			width: 41.66667% !important;
		  }
		  .mail .column td.five {
			width: 41.66667% !important;
		  }
		  .mail .columns td.six {
			width: 50% !important;
		  }
		  .mail .column td.six {
			width: 50% !important;
		  }
		  .mail .columns td.seven {
			width: 58.33333% !important;
		  }
		  .mail .column td.seven {
			width: 58.33333% !important;
		  }
		  .mail .columns td.eight {
			width: 66.66667% !important;
		  }
		  .mail .column td.eight {
			width: 66.66667% !important;
		  }
		  .mail .columns td.nine {
			width: 75% !important;
		  }
		  .mail .column td.nine {
			width: 75% !important;
		  }
		  .mail .columns td.ten {
			width: 83.33333% !important;
		  }
		  .mail .column td.ten {
			width: 83.33333% !important;
		  }
		  .mail .columns td.eleven {
			width: 91.66667% !important;
		  }
		  .mail .column td.eleven {
			width: 91.66667% !important;
		  }
		  .mail .columns td.twelve {
			width: 100% !important;
		  }
		  .mail .column td.twelve {
			width: 100% !important;
		  }
		  .mail td.offset-by-one {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-two {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-three {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-four {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-five {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-six {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-seven {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-eight {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-nine {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-ten {
			padding-left: 0 !important;
		  }
		  .mail td.offset-by-eleven {
			padding-left: 0 !important;
		  }
		  .mail table.columns td.expander {
			width: 1px !important;
		  }
		  .mail .right-text-pad {
			padding-left: 10px !important;
		  }
		  .mail .text-pad-right {
			padding-left: 10px !important;
		  }
		  .mail .left-text-pad {
			padding-right: 10px !important;
		  }
		  .mail .text-pad-left {
			padding-right: 10px !important;
		  }
		  .mail .hide-for-small {
			display: none !important;
		  }
		  .mail .show-for-desktop {
			display: none !important;
		  }
		  .mail .show-for-small {
			display: block !important; width: auto !important; overflow: visible !important;
		  }
		  .mail .hide-for-desktop {
			display: block !important; width: auto !important; overflow: visible !important;
		  }
		}
		</style>
		</head>
		<body style="width: 100% !important; min-width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; text-align: left; line-height: 1.3; background: #ffffff repeat center top; margin: 0; padding: 0;" bgcolor="#ffffff">
		<table class="mail" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; height: 100%; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: #ffffff repeat center top; margin: 0; padding: 0;" bgcolor="#ffffff">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td align="center" class="center" valign="top" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;">
		<center style="width: 100%; min-width: 580px;">
		<table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; max-width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top">
		<table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; background: #000000 repeat center top; padding: 0px;" bgcolor="#000000">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="wrapper first last" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; position: relative; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
		<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0px 0px 10px;" align="left" valign="top">
		<table class="table-block" width="100%" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: #000000 repeat center center; margin: 0; padding: 0px 10px;" align="left" bgcolor="#000000" valign="top">
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><span style="font-size: 36pt; color: rgb(255, 255, 255); font-family: Roboto, Tahoma, sans-serif;" data-mce-style="font-size: 36pt; color: #ffffff; font-family: Roboto, Tahoma, sans-serif;"><strong>PKCINEMA</strong></span></p>
		</td>
		</tr>
		</tbody>
		</table>


		</td>
		<td class="expander" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; visibility: hidden; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top"></td>
		</tr>
		</tbody>
		</table>
		</td>

		</tr>
		</tbody>
		</table>
		</td>
		</tr>
		</tbody>
		</table>
		<table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; max-width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top">
		<table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; background: #000000 repeat center top; padding: 0px;" bgcolor="#000000">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="wrapper first last" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; position: relative; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
		<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0px 0px 10px;" align="left" valign="top">
		<table class="table-block" width="100%" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: #000000 repeat center center; margin: 0; padding: 0px 10px;" align="left" bgcolor="#000000" valign="top">
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><span style="font-size: 26pt;" data-mce-style="font-size: 26pt;"><span color="#ffffff" data-mce-style="color: #ffffff;" style="color: #ffffff;">Здравствуйте ''' + str(
            name
        ) + '''!</span></span></p>
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><span style="font-size: 16pt;" data-mce-style="font-size: 16pt;"><span color="#ffffff" data-mce-style="color: #ffffff;" style="color: #ffffff;">Вы успешно забронировали билеты)</span></span></p>
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><span color="#ffffff" data-mce-style="color: #ffffff;" style="color: #ffffff;"><span style="font-size: 21.3333px;" data-mce-style="font-size: 21.3333px;">Ваши места: ''' + setMestaforEmail(
            '; '.join(booked)
        ) + '''</span></span></p>
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><span color="#ffffff" data-mce-style="color: #ffffff;" style="color: #ffffff;"><span style="font-size: 21.3333px;" data-mce-style="font-size: 21.3333px;">Мероприятие: ''' + str(
            merop
        ) + '''</span></span></p>
		<p style="text-align: center; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0 0 10px; padding: 0;" data-mce-style="text-align: center;" align="center"><br></p>
		</td>
		</tr>
		</tbody>
		</table>

		<table class="table-full" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; background: transparent repeat center center; padding: 0;" width="100%" bgcolor="transparent">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td height="%" style="width: 22% !important; height: % !important; word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: repeat center top; margin: 0; padding: 0;" width="22%" align="left" valign="top"></td>
		<td height="%" style="width: 57% !important; height: % !important; word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: repeat center top; margin: 0; padding: 0;" width="57%" align="left" valign="top">
		<table class="button" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; overflow: hidden; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: center; width: auto !important; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: initial !important; display: block; margin: 0; padding: 0px;" align="center" valign="top">
		<!--[if mso]>
		<p style='line-height:0;margin:0;'>&nbsp;</p>
		<v:roundrect arcsize='5%' fill='t' fillcolor='#bd3535' href="''' + str(
            link
        ) + '''" stroke='f' strokecolor='' style='v-text-anchor:middle;width:331px;height:55px;' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word'>
		<w:anchorlock>
		<center style='color: #FFF; font-family:sans-serif; font-size:13px; font-weight:bold; mso-line-height-rule:exactly; mso-text-raise:4px'>
		Отменить Бронирование
		</center>
		</w:anchorlock>
		</v:roundrect>
		<![endif]-->
		<!--[if !mso]>
		<!---->
		<a href="''' + str(
            link
        ) + '''" style="line-height: 20px; font-size: 20px !important; width: auto; display: block; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; color: #ffffff; text-decoration: none; font-weight: bold; font-family: Helvetica, Arial, sans-serif; height: 100%; background: #bd3535 repeat center center; padding: 15px 10px;">Отменить Бронирование</a>
		<!-- <![endif]-->
		<!--[endif]---->
		</td>
		</tr>
		</tbody>
		</table>

		</td>
		<td height="%" style="width: 21% !important; height: % !important; word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; background: repeat center top; margin: 0; padding: 0;" width="21%" align="left" valign="top"></td>
		</tr>
		</tbody>
		</table>


		</td>
		<td class="expander" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; visibility: hidden; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top"></td>
		</tr>
		</tbody>
		</table>
		</td>

		</tr>
		</tbody>
		</table>
		</td>
		</tr>
		</tbody>
		</table>

		<table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; max-width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top">
		<table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; background: transparent repeat center top; padding: 0px;" bgcolor="transparent">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="wrapper first last" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; position: relative; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
		<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0px 0px 10px;" align="left" valign="top">
		<table width="100%" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; padding: 0;">
		<tbody>
		<tr style="vertical-align: top; text-align: left; padding: 0;" align="left">
		<td class="center" style="text-align: center; word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; width: 100%; font-weight: normal; line-height: 1.3; background: transparent repeat center center; margin: 0; padding: 0px;" align="center" bgcolor="transparent" valign="top">
		</td>
		</tr>
		</tbody>
		</table>


		</td>
		<td class="expander" style="word-break: break-word; -webkit-hyphens: none; -moz-hyphens: none; hyphens: none; border-collapse: collapse !important; vertical-align: top; text-align: left; width: 100%; visibility: hidden; color: #222222; font-family: Helvetica, Arial, sans-serif; font-weight: normal; font-size: 14px; line-height: 1.3; margin: 0; padding: 0;" align="left" valign="top"></td>
		</tr>
		</tbody>
		</table>
		</td>

		</tr>
		</tbody>
		</table>
		</td>
		</tr>
		</tbody>
		</table>

		</center>
		</td>
		</tr>
		</tbody>
		</table>




			</body>
		</html>
'''
        email1 = EmailMessage('Бронирование', data, to=[str(email)])
        email1.content_subtype = "html"

        for i in range(len(booked)):
            qr_link = "http://127.0.0.1:8000/prov/?email=" + email + "&" + "merop=" + merop + "&" + "name=" + name + "&" + "place=" + booked[
                i]
            print(qr_link)
            PDF(merop, name, booked)
            CreateQr(qr_link)

            email1.attach_file(r'media/pdf/destination' + str(i) + '.pdf')
        email1.send()

        for id in zap:
            print(zap[id].username, zap[id].email, zap[id].places,
                  zap[id].mero)

        return HttpResponse("бронь")

    if request.GET.get("Command") == "DeleteBooking":
        Booking.objects.all().delete()
        return HttpResponse("Все места удалены, милорд")
Beispiel #43
0
def notify_pwa_install(member):
    service = get_service_instance()
    install_count = PWAProfile.objects.filter(
        service=service, installed_on__isnull=False).count()
    if member:
        member_detail_view = getattr(settings, 'MEMBER_DETAIL_VIEW', None)
        if member_detail_view:
            target_page = reverse(member_detail_view, args=(member.id, ))
        else:
            target_page = ikwenize(reverse('ikwen:profile',
                                           args=(member.id, )))
    else:
        target_page = None

    for staff in Member.objects.filter(is_staff=True):
        if staff.language:
            activate(staff.language)
        else:
            activate('en')

        if member:
            title = member.full_name
            body = _(
                "This customer just installed you app %(app_name)s. You can call or text to say thank you. \n"
                "Now you have your app installed by %(install_count)d people" %
                {
                    'app_name': service.project_name,
                    'install_count': install_count
                })
        else:
            title = _("New app install")
            body = _(
                "An anonymous visitor just installed your app %(app_name)s. \n"
                "Now you have it installed by %(install_count)d people" % {
                    'app_name': service.project_name,
                    'install_count': install_count
                })

        notification = {
            'title': title,
            'body': body,
            'target': target_page,
            'badge': ikwen_settings.MEDIA_URL + 'icons/android-icon-96x96.png',
            'icon': ikwen_settings.MEDIA_URL + 'icons/android-icon-512x512.png'
        }

        ikwen = Service.objects.using(UMBRELLA).get(
            pk=ikwen_settings.IKWEN_SERVICE_ID)
        qs = PWAProfile.objects.using(UMBRELLA).filter(service=ikwen,
                                                       member=staff)
        if qs.count() > 0:
            for pwa_profile in qs:
                try:
                    webpush(json.loads(pwa_profile.push_subscription),
                            json.dumps(notification),
                            vapid_private_key=ikwen_settings.PUSH_PRIVATE_KEY,
                            vapid_claims={"sub": "mailto:[email protected]"},
                            ttl=86400,
                            timeout=60)
                except:
                    pass
        else:
            try:
                extra_context = {
                    'member_name': staff.first_name,
                    'message': body
                }
                if target_page:
                    extra_context['cta_url'] = service.url + target_page
                html_content = get_mail_content(
                    title,
                    template_name='core/mails/pwa_installed_notification.html',
                    extra_context=extra_context)
                sender = 'ikwen <*****@*****.**>'
                msg = EmailMessage(title, html_content, sender, [staff.email])
                msg.content_subtype = "html"
                msg.send()
            except:
                logger.error("%s - Failed to send order confirmation email." %
                             service,
                             exc_info=True)
    def handle(self, *args, **options):

        #assume dry run condition
        is_dry_run = True
        if os.environ['CVAR_DRY_RUN'] == 'False':
            is_dry_run = False

        #sets the day of the month that late fee emails wills trigger
        late_fee_activation_day = 11

        date_today = date.today()
        invoiced_students = []
        for student in Student.objects.all():

            if student not in invoiced_students:

                invoice_line_items = []
                invoice_billing_emails = []
                has_unpaid_invoices = False
                late_fee_added_for_billing_period = False
                for invoice in student.invoice_set.filter(date_created__gte=date((date_today - relativedelta(months=1)).year, 12 if date_today.month == 1 else date_today.month - 1, 1), date_created__lt=date((date_today + relativedelta(months=1)).year, 1 if date_today.month == 12 else date_today.month + 1, 1)):
                    
                    #if not invoice.summary.startswith("Late Fee"):
                    invoice_line_items.append([
                        invoice.date_created,
                        invoice.date_due,
                        invoice.student,
                        invoice.summary,
                        invoice.travel_fee,
                        invoice.subtotal,
                        invoice.subtotal + invoice.travel_fee,
                        invoice.payment_status,
                    ])
                    if invoice.payment_status == Invoice.PAYMENT_STATUS_UNPAID:
                        has_unpaid_invoices = True
                    if invoice.summary == "Late Fee (%s)" % (date_today.strftime("%B"),) and invoice.date_due == date(date_today.year, date_today.month, 1):
                        late_fee_added_for_billing_period = True

                invoiced_students.append(student)
                if student.is_billing_contact and student.user.email:
                    invoice_billing_emails.append(student.user.email)

                #sending one invoice per family
                for parent in student.parents.all():
                    for student in parent.student_set.all():

                        if student not in invoiced_students:

                            #currently, email needs to print all invoice details from last month and current month
                            for invoice in student.invoice_set.filter(date_created__gte=date((date_today - relativedelta(months=1)).year, 12 if date_today.month == 1 else date_today.month - 1, 1), date_created__lt=date((date_today + relativedelta(months=1)).year, 1 if date_today.month == 12 else date_today.month + 1, 1)):

                                #if not invoice.summary.startswith("Late Fee"):
                                invoice_line_items.append([
                                    invoice.date_created,
                                    invoice.date_due,
                                    invoice.student,
                                    invoice.summary,
                                    invoice.travel_fee,
                                    invoice.subtotal,
                                    invoice.subtotal + invoice.travel_fee,
                                    invoice.payment_status,
                                ])
                                if invoice.payment_status == Invoice.PAYMENT_STATUS_UNPAID:
                                    has_unpaid_invoices = True
                                if invoice.summary == "Late Fee (%s)" % (date_today.strftime("%B"),) and invoice.date_due == date(date_today.year, date_today.month, 1):
                                    late_fee_added_for_billing_period = True

                            invoiced_students.append(student)
                            if student.is_billing_contact and student.user.email:
                                invoice_billing_emails.append(student.user.email)

                    if parent.is_billing_contact and parent.user.email:
                        invoice_billing_emails.append(parent.user.email)


                if not invoice_line_items:
                    continue
                elif has_unpaid_invoices and date_today.day == late_fee_activation_day and not late_fee_added_for_billing_period:
                    
                    #add late fee invoice to system and invoice_line_items
                    late_fee_invoice = Invoice.objects.create(
                        student=student,
                        summary="Late Fee (%s)" % (date_today.strftime("%B"),),
                        subtotal=Decimal('20.00'),
                    )

                    invoice_line_items.append([
                        late_fee_invoice.date_created,
                        late_fee_invoice.date_due,
                        late_fee_invoice.student,
                        late_fee_invoice.summary,
                        late_fee_invoice.travel_fee,
                        late_fee_invoice.subtotal,
                        late_fee_invoice.subtotal + late_fee_invoice.travel_fee,
                        late_fee_invoice.payment_status,
                    ])

                #format the email greeting
                billing_email_greeting = "Parents and Students,"
                if User.objects.filter(email__in=invoice_billing_emails).exclude(first_name__exact="-not found-").exists():
                    billing_email_greeting = ""
                    for contact in User.objects.filter(email__in=invoice_billing_emails).exclude(first_name__exact="-not found-"):
                        billing_email_greeting += "%s," % (contact.first_name,)
                    
                    billing_email_greeting = billing_email_greeting.replace(",", " and ", billing_email_greeting.count(',') - 1)
     
                #send the email now
                amount_due = Decimal('0.00')
                html_message = "<html>Hello %s<br /><br />The following is an invoice summary for all lessons billed and credited up to %s:<br /><br /><table><thead><tr><td>Invoice Date</td><td>Due Date</td><td>Student Name</td><td>Summary</td><td>Travel Fee</td><td>Subtotal</td><td>Total</td><td>Status</td></tr></thead>" % (billing_email_greeting, date_today.strftime("%A %B %-d, %Y"),)
                for line_item in sorted(invoice_line_items, key=itemgetter(0)):
                    
                    line_color = 'darkgrey'
                    if line_item[7] == Invoice.PAYMENT_STATUS_UNPAID:
                        amount_due += line_item[6]
                        line_color = 'firebrick'
                    elif line_item[7] == Invoice.PAYMENT_STATUS_PAID:
                        line_color = 'forestgreen'
                    elif line_item[7] == Invoice.PAYMENT_STATUS_CREDIT:
                        amount_due -= line_item[6]
                        line_color = 'deepskyblue'

                    html_message += "<tr style='color: %s;'><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>$%s</td><td>$%s</td><td><b>$%s</b></td><td>%s</td></tr>" % (
                        line_color,
                        line_item[0],
                        line_item[1],
                        line_item[2],
                        line_item[3],
                        line_item[4],
                        line_item[5],
                        line_item[6],
                        line_item[7],
                    )
                html_message += "<tr style='color: %s;'><td colspan='6'></td><td><b>$%s</b></td><td>AMOUNT %s</td></tr></table><br />Please reply to this email if any of the amounts above look incomplete or incorrect; late fees for unpaid invoices are processed on the 11th of every month.<br /><br />Thank you,<br /><br />-Administrator</html>" % ('deepskyblue' if amount_due < 0 else 'firebrick', amount_due if amount_due != 0 else '0.00', 'CREDITED' if amount_due < 0 else 'DUE',)

                if is_dry_run:
                    invoice_billing_emails = [os.environ['CVAR_DRY_RUN_EMAIL']]

                invoice_email = EmailMessage(subject="%s Invoice Summary" % (date_today.strftime("%B"),), body=html_message, to=invoice_billing_emails)
                invoice_email.content_subtype = "html"
                invoice_email.send(fail_silently=False)

        self.stdout.write(self.style.SUCCESS("Successfully processed all billing alerts"))
Beispiel #45
0
 def mail():
     message = EmailMessage(subject, html_message, email_from, rec)
     message.content_subtype = 'html'
     message.send()
Beispiel #46
0
def checkout(request):
    """
    Validation and processing of the form(s) filled out
    within the checkout submission.
    On any payment form errors, return a blank payment form
    """
    if request.method=='POST':
        order_form = OrderForm(request.POST)
        payment_form = PaymentForm(request.POST)
        
        if order_form.is_valid() and payment_form.is_valid():
            # save the order
            order = order_form.save(commit=False)
            order.date = timezone.now()
            order.save()
            saved_order = get_object_or_404(Order, pk=order.id)
            
            # add the cart items to the order
            cart = request.session.get('cart', {})
            total = 0
            for id, quantity in cart.items():
                product = get_object_or_404(Product, pk=id)
                total_item_price = quantity * product.price
                total += quantity * product.price
                order_item = OrderItem(
                    order = order,
                    product = product,
                    quantity = quantity,
                    total_item_price = total_item_price,
                    )
                order_item.save()

            try:
                # Charge the customer
                customer = stripe.Charge.create(
                    amount = int(total * 100),
                    currency = "EUR",
                    description = order_form.cleaned_data['email_address'],
                    card = payment_form.cleaned_data['stripe_id'],
                    )
                
                if customer.paid:
                    try:
                        # send a confirmation mail to the customer
                        order_items = OrderItem.objects.filter(
                            order=saved_order)
                        site = get_current_site(request)
                        message = render_to_string(
                            'confirmation.html',{
                                'order':saved_order,
                                'order_items':order_items,
                                'total': total,
                                'site':site.domain,
                            })
                        mail_subject = 'Your order: BSS-%s' % saved_order.id
                        email_to = order_form.cleaned_data['email_address']
                        email = EmailMessage(
                            mail_subject, message, to=[email_to])
                        email.content_subtype = 'html'
                        email.send()
                    except BadHeaderError:
                        return HttpResponse('Invalid header found.')
                    
                    messages.success(request, 
                        'Your order has been placed.<br>'
                        + ' A confirmation email should arrive shortly.',
                        extra_tags='safe',
                        )
                    request.session['cart'] = {}
                    return redirect(reverse('products'))
                else:
                    messages.error(request, 
                        'Unable to take payment at this time, '
                        + 'please try again later')
                    payment_form = PaymentForm()
                        
            except stripe.error.CardError:
                messages.error(request, 
                    'Your payment failed, your card was declined.'
                    )
                payment_form = PaymentForm()
        else:
            messages.error(request, 
                'We were unable to take a payment with the card you entered')
            payment_form = PaymentForm()
    else:
        order_form = OrderForm()
        payment_form = PaymentForm()
        
    return render(request, 'checkout.html', {
        'order_form': order_form, 
        'payment_form':payment_form, 
        'stripe_pk':settings.STRIPE_PK}
        )
Beispiel #47
0
def confirm(request):
    products = Product.objects.filter(active=True).all()

    if request.method == 'POST':
        store = request.POST.get("store")
        stay = request.POST.get("stay")
        name = request.POST.get("name")
        phone = request.POST.get("phone")
        email = request.POST.get("email")

        # save customer and order
        if email == None:  # customers order with staff won't save to database
            # save order
            order = Order(store=store, stay=stay, status='Pending')
            order.save()
        else:
            # check if customer has shopped once
            customer, created = Customer.objects.get_or_create(email=email)

            customer.name = name
            customer.phone = phone
            customer.save()

            # save order
            order = Order(
                customer=customer,
                store=store,
                stay=stay,
                status='Pending',
            )
            order.save()

        # save orderItem
        for product in products:
            if request.POST.get(f'{product.id} hot') == None:
                pass  # ignore empty value
            else:
                product.data_hot = request.POST.get(f'{product.id} hot')
                hot = OrderItem(order=order,
                                product=product,
                                hotOrCold='Hot',
                                qty=product.data_hot)
                hot.save()
            if request.POST.get(f'{product.id} cold') == None:
                pass  # ignore empty value
            else:
                product.data_cold = request.POST.get(f'{product.id} cold')
                cold = OrderItem(order=order,
                                 product=product,
                                 hotOrCold='Cold',
                                 qty=product.data_cold)
                cold.save()

        # send email
        if email != None:
            template = get_template('main/email.html').render({
                'order': order,
            })
            emailmsg = EmailMessage(
                'Order Confirmaion from TEA Time',  # subject
                template,  # body
                settings.EMAIL_HOST_USER,  # sender
                [email],  # reciever
            )
            emailmsg.content_subtype = 'html'
            emailmsg.fail_silently = False
            emailmsg.send()

    return render(
        request, 'main/confirm.html', {
            'store': store,
            'stay': stay,
            'phone': phone,
            'email': email,
            'order': order,
        })
Beispiel #48
0
                # list of occurrence of professional in day, exclude unmarked and rescheduled.
                for x in Occurrence.objects.filter(start_time__year=y, start_time__month=m, start_time__day=d,event__referral__professional=pr,\
                        event__referral__organization=org).order_by('start_time').\
                        exclude(scheduleoccurrence__occurrenceconfirmation__presence=4).\
                        exclude(scheduleoccurrence__occurrenceconfirmation__presence=5):
                    oc_list.append(x)

                # send email if not empty list for both
                if to and oc_list:
                    title = u"Resumo dos seus eventos para %s, %s.\n\n" % (
                        week_days[dt.isoweekday()], dt.strftime('%d %b %Y'))

                    # render html email
                    text = Context({
                        'oc_list': oc_list,
                        'title': title,
                        'org': org,
                        'showdt': False
                    })
                    template = get_template(
                        "schedule/schedule_notify_careprofessional.html"
                    ).render(text)
                    # sendmail
                    msg = EmailMessage()
                    msg.content_subtype = 'html'
                    msg.encoding = "utf-8"
                    msg.subject = u"GestorPsi - Resumo diário dos eventos."
                    msg.body = template
                    msg.to = to
                    msg.send()
Beispiel #49
0
def remind_parents():

    app = Application.objects.get(slug='foulassi')
    try:
        foulassi = Service.objects.using('umbrella').get(project_name_slug='foulassi')
    except:
        foulassi = None

    for school in Service.objects.filter(app=app):
        diff = datetime.now() - school.since
        if not DEBUG and diff.days < 7: # school should exist at least 1 week ago
            print("Skipping school %s" % school.project_name)
            continue

        db = school.database
        add_database(db)

        school_config = SchoolConfig.objects.using(db).get(service=school)

        for classroom in Classroom.objects.using(db).all():
            now = datetime.now()
            for assignment in classroom.assignment_set.filter(deadline=now.date() + timedelta(1)):
                for student in Student.objects.using(db).filter(classroom=classroom):
                    try:
                        # Test whether the homework was submitted
                        student.homework_set.get(assignment=assignment)
                        continue
                    except:
                        for parent in Parent.objects.using(db).select_related('member').filter(student=student):
                            try:
                                parent_email = parent.get_email()
                                parent_name = parent.get_name()
                            except:
                                logger.error('A parent of %s has no contacts' % student.first_name)
                                continue
                            company_name = school_config.company_name
                            sender = '%s via ikwen Foulassi <*****@*****.**>' % company_name
                            try:
                                cta_url = 'https://go.ikwen.com' + reverse('foulassi:change_homework', args=(school_config.company_name_slug, student.pk, assignment.pk))
                            except:
                                cta_url = ''
                            member = parent.member
                            if member:
                                activate(member.language)
                            student_name = student.first_name
                            subject = _("Less than 24 hours remain to turn back your kid's homework")
                            extra_context = {'parent_name': parent_name, 'cta_url': cta_url,
                                             'school_name': company_name,
                                             'student_name': student_name,
                                             'assignment': assignment,
                                             }
                            if DEBUG:
                                html_content = get_mail_content(subject,
                                                                template_name='foulassi/mails/unsubmitted_homework.html',
                                                                extra_context=extra_context)
                            else:
                                try:
                                    html_content = get_mail_content(subject,
                                                                    template_name='foulassi/mails/unsubmitted_homework.html',
                                                                    extra_context=extra_context)
                                except:
                                    logger.error("Could not generate HTML content from template", exc_info=True)
                                    continue

                            msg = EmailMessage(subject, html_content, sender, [parent_email, '*****@*****.**', '*****@*****.**'])
                            msg.content_subtype = "html"
                            print("Sending email to %s ..." % parent_email)
                            try:
                                msg.send()
                                print("Email sent")
                            except Exception as e:
                                print e.message

                            body = _("%(student_name)s has not yet submit his homework of %(subject)s "
                                     % {'student_name': student_name, 'subject': subject})
                            if member:
                                send_push(foulassi, member, subject, body, cta_url)
Beispiel #50
0
def detect_deadlock(*args):
    # 检查实例,并生生成实例死锁记录的命令
    # 使用本机的数据库作为死锁记录
    # 库名:auditsql,表名:dbaudit_deadlocks_records
    command = "/usr/bin/pt-deadlock-logger --user={user} --password={password} --host={host} --port={port} " \
              "--no-version-check --create-dest-table " \
              "--dest h=localhost,u=root,p=123.com,D=sqlaudit,t=sqlaudit_deadlocks_records --iterations 1"

    query = "SELECT id, `user`, `password`, `host`, `port` FROM sqlaudit_mysql_schemas " \
            "WHERE sqlaudit_mysql_schemas.is_master = 1 group by host,port"

    for row in MysqlSchemas.objects.raw(query):
        format_command = command.format(user=row.user,
                                        password=row.password,
                                        host=row.host,
                                        port=row.port)
        if not DeadlockCommand.objects.filter(schema_id=row.id):
            DeadlockCommand.objects.create(schema_id=row.id,
                                           command=format_command)

    # 轮询探测死锁
    for row in DeadlockCommand.objects.all():
        process = subprocess.Popen(row.command, shell=True)
        process.wait()

    # 检查死锁,并发送报告
    i = 0
    step = 2
    result = []
    data = list(DeadlockRecord.objects.filter(is_pull=0).values())
    while i <= (len(data) - step):
        result.append({'data': [data[i], data[i + 1]]})
        i += step

    format_deadlock_data = ''
    j = 1
    for row in result:
        double_data = ''
        for i in row['data']:
            text = f"主机:{i['server']}\n" \
                   f"时间: {i['ts']}\n" \
                   f"线程ID: {i['thread']}\n" \
                   f"事务ID: {i['txn_id']}\n" \
                   f"事务激活时间: {i['txn_time']}\n" \
                   f"用户名: {i['user']}\n" \
                   f"主机名: {i['hostname']}\n" \
                   f"IP: {i['ip']}\n" \
                   f"库名: {i['db']}\n" \
                   f"表名: {i['tbl']} \n" \
                   f"发生死锁的索引: {i['idx']}\n" \
                   f"锁类型: {i['lock_type']}\n" \
                   f"锁模式: {i['lock_mode']}\n" \
                   f"请求锁: {i['wait_hold']}\n" \
                   f"是否回滚: {'否' if i['victim'] == 0 else '是'}\n" \
                   f"查询: {i['query']}\n\n"
            double_data += text
            DeadlockRecord.objects.filter(id=i['id']).update(is_pull=1)

        format_deadlock_data += ''.join((f'## 死锁记录{j} ##:\n', double_data))
        j += 1

    if result:
        # 判断系统是否开启了相关通知
        # 发送邮件通知
        if SysConfig.objects.get(key='email_push').is_enabled == '0':
            email_html_body = render_to_string(
                'mailnotice/_deadlocks_mail.html', {
                    'data': result,
                })

            # 发送邮件
            title = '探测到新的死锁'
            msg = EmailMessage(subject=title,
                               body=email_html_body,
                               from_email=EMAIL_FROM,
                               to=list(args))
            msg.content_subtype = "html"
            msg.send()

        # 发送钉钉通知
        if SysConfig.objects.get(key='dingding_push').is_enabled == '0':
            webhook = SysConfig.objects.get(key='dingding_push').value
            xiaoding = DingtalkChatbot(webhook)

            check_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            msg = '\n'.join((f'【警告 ◕﹏◕,探测到新的死锁记录,探测时间:{check_time}】\n',
                             format_deadlock_data))

            xiaoding.send_text(msg=msg, is_at_all=True)
def index(request, req_blood):
    current_site = get_current_site(request)
    if request.method == 'POST':
        form = RequestorForm(request.POST)

        if form.is_valid():
            name = form.cleaned_data['name']
            phone = form.cleaned_data['phone']
            email = form.cleaned_data['email']
            reason = form.cleaned_data['reason']
            city = form.cleaned_data['city']
            state = form.cleaned_data['state']

            # blood = request.POST.get('blood')
            blood = req_blood
            print(blood)

            if UserAddress.objects.filter(
                    blood=blood,
                    city=city,
                    state=state,
            ).count() == 0:
                return render(request, 'requestblood/sorry.html',
                              {'error': 'Sorry.no donor found near you!'})

            print(date.today())
            print(date)
            # print(Requestor.objects.filter(name=name, phone=phone, date=date.today()))
            if Requestor.objects.filter(name=name,
                                        phone=phone,
                                        date=date.today(),
                                        blood=blood).exists():
                return render(
                    request, 'requestblood/sorry.html', {
                        'error':
                        'Your request has already been sent. Please wait for donor\'s response'
                    })

            else:
                requestor = Requestor.objects.create(name=name,
                                                     blood=blood,
                                                     phone=phone,
                                                     email=email,
                                                     reason=reason,
                                                     state=state,
                                                     city=city)

                query = UserAddress.objects.filter(blood=blood, city=city)
                result = UserAddress.objects.none()

                for donor in query:
                    a = UserHistory.objects.filter(user=donor.user)
                    recent = a.count() - 1

                    b = UserAddress.objects.get(user=a[0].user)
                    if a[recent].donation_date and (datetime.date.today() -
                                                    b.birth).days > 6570:
                        if (datetime.date.today() -
                                a[recent].donation_date.date()).days > 90:
                            result |= a
                subject = 'Request for blood'
                print(result)

                from_email = requestor.email

                for donor in result:

                    to_email = [
                        donor.user.email,
                    ]
                    link = 'http://' + current_site.domain + '/donate/'

                    context = {
                        'link': link,
                        'username': donor.user.username,
                        'requestor': requestor.name,
                        'reason': requestor.reason,
                        'phone': requestor.phone,
                        'email': requestor.email,
                    }
                    message = render_to_string('requestblood/email.html',
                                               context)
                    msg = EmailMessage(subject,
                                       message,
                                       to=[to_email],
                                       from_email=from_email)
                    msg.content_subtype = 'html'

                    try:

                        msg.send()
                        print('Successful')
                    except:
                        print('\nUnsuccessful attempt')
                        return render(request, 'requestblood/sorry.html', {
                            'error':
                            'There was an error in sending the email'
                        })

                return render(request, 'requestblood/response.html')

    else:
        form = RequestorForm()

    return render(request, 'requestblood/index.html', {
        'form': form,
        'blood': req_blood
    })
Beispiel #52
0
def update(request, item_id):
    all_items = Items.objects.all()
    cur_item = Items.objects.get(pk=item_id)
    user_name = User.objects.get(username=request.user.username)
    print(user_name)
    credits = Credits.objects.get(name=user_name)
    c1 = Credits.objects.get(name=cur_item.seller)
    score = credits.credit
    # print(credits)
    bid = request.POST['bid_value']
    if int(score) >= int(bid):
        html_content = "<strong>Your current bid has been overtaken by someone.</strong>"
        email = EmailMessage('Auction House:Sad news',
                             html_content,
                             to=['*****@*****.**'])
        email.content_subtype = "html"
        email.send()
        if int(bid) in range(int(
                cur_item.cur_highest_bid), int(
                    cur_item.buy_now_price)) and int(bid) > cur_item.min_price:

            cur_item.cur_highest_bid = bid
            cur_item.cur_highest_bidder = User.objects.get(
                username=request.user.username)
            cur_item.save()
            #credits.credit = int(credits.credit) - int(bid)
            #credits.save()
            #c1.credit = int(c1.credit) + int(bid)
            #c1.save()

            context = {
                'all_items': all_items,
            }
            return render(request, 'Browse/index.html', context)
        elif int(bid) >= int(cur_item.buy_now_price):
            cur_item.cur_highest_bid = bid
            cur_item.cur_highest_bidder = User.objects.get(
                username=request.user.username)
            credits.credit = int(credits.credit) - int(bid)
            credits.save()
            c1.credit = int(c1.credit) + int(bid)
            c1.save()
            cur_item.save()
            bt = Bought()
            bt.seller = cur_item.seller
            bt.item_id = cur_item.item_id
            bt.item_logo = cur_item.item_logo
            bt.item_name = cur_item.item_name
            bt.item_desc = cur_item.item_desc
            bt.buyer = cur_item.cur_highest_bidder
            bt.cur_highest_bid = cur_item.cur_highest_bid
            bt.created_on = cur_item.created_on
            bt.expiration = cur_item.expiration
            bt.min_price = cur_item.min_price
            bt.buy_now_price = cur_item.buy_now_price
            bt.save()
            cur_item.delete()
            messages.error(request, 'Congrats, you won!.')
            #messages.error(request, 'Congrats, you won!.')
            #cur_item = Items.objects.all()
            #cur_item = Items.objects.get(pk=item_id)
            context = {
                'all_items': all_items,
            }

            return render(request, 'Browse/index.html', context)
        elif int(cur_item.cur_highest_bid) > int(bid) or int(
                cur_item.min_price) > int(bid):

            messages.error(request, 'Bid rejected.')
            cur_item = Items.objects.get(pk=item_id)
            context = {'cur_item': cur_item}
            return render(request, 'Browse/details.html', context)

    elif int(score) < int(bid):
        messages.error(request, 'You do not have enough credits!')
        cur_item = Items.objects.get(pk=item_id)
        context = {'cur_item': cur_item}
        return render(request, 'Browse/details.html', context)
Beispiel #53
0
def dispatch_mail(to_list, subject, html_content, from_email='*****@*****.**'):
    msg = EmailMessage(subject, html_content, from_email, [to_list])
    msg.content_subtype = "html"  # Main content is now text/html
    return msg.send()
Beispiel #54
0
def send_register_eamil(email, send_type="register"):
    """发送注册邮件"""
    # 发送之前先保存到数据库,到时候查询链接是否存在
    # 实例化一个EmailVerifyRecord对象
    email_record = EmailVerifyRecord()
    # 生成随机的code放入链接
    if send_type == "update_email":
        code = random_str(4)
    else:
        code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type

    email_record.save()

    # 定义邮件内容:
    email_title = ""
    email_body = ""

    if send_type == "register":
        email_title = "慕课小站 注册激活链接"
        # email_body = "欢迎注册慕课小站:  请点击下面的链接激活你的账号: http://127.0.0.1:8000/active/{0}".format(code)

        absolute_url = reverse("user_active", kwargs={"active_code": code})
        print(absolute_url)
        email_url = settings.ACTIVE_EMAIL_URL + "/" + absolute_url
        print(email_url)
        email_body = loader.render_to_string(
            "email_register.html",  # 需要渲染的html模板
            {
                "active_code": code  # 参数
                }
            )

        msg = EmailMessage(email_title, email_body, EMAIL_FROM, [email])
        msg.content_subtype = "html"
        send_status = msg.send()
        # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list
        # send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])

        # 如果发送成功
        if send_status:
            pass
    elif send_type == "forget":
        email_title = "慕课小站 找回密码链接"
        email_body = loader.render_to_string(
            "email_forget.html",  # 需要渲染的html模板
            {
                "active_code": code  # 参数
            }
        )
        msg = EmailMessage(email_title, email_body, EMAIL_FROM, [email])
        msg.content_subtype = "html"
        send_status = msg.send()
    elif send_type == "update_email":
        email_title = "慕课小站 修改邮箱验证码"
        email_body = loader.render_to_string(
            "email_update_email.html",  # 需要渲染的html模板
            {
                "active_code": code  # 参数
            }
        )
        msg = EmailMessage(email_title, email_body, EMAIL_FROM, [email])
        msg.content_subtype = "html"
        send_status = msg.send()
Beispiel #55
0
def aorderprocessringtoneorderpaymentcheck(request):
    APP_PATH = os.path.dirname(aid.__file__)
    print("APP_PATH: " + APP_PATH)

    ectoken = request.POST['ectoken']
    print("ectoken from check: " + ectoken)

    cursor3 = connection.cursor()
    cursor3.execute(
        "SELECT "
        "paypalpaymentid_tbladoc, "
        "Docid_tbladoc "
        "FROM aid_tbladoc "
        ""
        "WHERE paypalectoken_tbladoc=%s ", [ectoken])
    results = cursor3.fetchall()
    for x in results:
        paymentidfromsql = x[0]
        cordocid = x[1]
    print("paymentid from check: " + paymentidfromsql)

    payment = paypalrestsdk.Payment.find(paymentidfromsql)
    print("from check: " + str(payment.payer.status))
    print("paymentdetails from check with single quotes: " + str(payment))
    paymentwithdoublequotes = str(payment).replace("\'", "\"")
    print("paymentdetails from check with double quotes: " +
          paymentwithdoublequotes)
    parsed = json.loads(paymentwithdoublequotes)
    print("parsedpayment: " + json.dumps(parsed, indent=4, sort_keys=True))

    print("paymentcurrency: " + payment.transactions[0]["amount"].currency)
    print("paymenttotal: " + payment.transactions[0]["amount"].total)
    payeremail = payment.payer.payer_info.email
    payerfirstname = payment.payer.payer_info.first_name
    description = payment.transactions[0][
        "description"]  #ringtonemasterfileid from paypal description
    descriptionsplitted = description.split(", ")
    ringtonemasterfileid = descriptionsplitted[0]
    emailtosend = descriptionsplitted[1]
    print("payeremail: " + payeremail)
    print("ringtonemasterfileid: " + ringtonemasterfileid)
    print("emailtosend: " + emailtosend)

    BASE_DIR = settings.BASE_DIR

    #preparing ringtonemodifiedfile to send begin (to send Spice_Girls_Wannabe.mid instead of 3.mid - filename preparation)
    subprocess.call(
        'if [ ! -d "' + BASE_DIR + '/ringtonemodifiedfiles/' + ectoken +
        '" ]; then mkdir ' + BASE_DIR + '/ringtonemodifiedfiles/' + ectoken +
        '  ;else rm -rf ' + BASE_DIR + '/ringtonemodifiedfiles/' + ectoken +
        ' && mkdir ' + BASE_DIR + '/ringtonemodifiedfiles/' + ectoken +
        ';  fi',
        shell=True)
    subprocess.call(
        'find ' + BASE_DIR +
        '/ringtonemodifiedfiles/* -mmin +59 -exec rm -rf {} \;',
        shell=True
    )  #delete older than 1 hour /ringtonemodifiedfiles/ directories (with ringtonemodified files into those)

    cursor1 = connection.cursor()
    cursor1.execute(
        "SELECT "
        "ringtonemasterfileid_tblaringtonemasterfiles, "
        "title_tblaringtonemasterfiles "
        "FROM aid_tblaringtonemasterfiles "
        "WHERE ringtonemasterfileid_tblaringtonemasterfiles = %s",
        [ringtonemasterfileid])
    ringtonemasterfiles = cursor1.fetchall()
    for x in ringtonemasterfiles:
        ringtonemasterfiletitle = x[1]

        # get cornumber from cor begin
        cursor3 = connection.cursor()
        cursor3.execute(
            "SELECT "
            "Docid_tblaDoc "
            "FROM aid_tbladoc "
            "WHERE paypalectoken_tbladoc=%s", [ectoken])
        results = cursor3.fetchall()
        for x in results:
            cornumber = x[0]

# get cornumber from cor end

# making ringtonemodifiedfilewithtitle begin

    ringtonemasterfilenamewithid = APP_PATH + '/static/ringtonemasterfiles/' + str(
        ringtonemasterfileid) + '.mp3'
    file = open(ringtonemasterfilenamewithid, 'rb')
    ringtonemasterfilecontent = file.read()
    file.close()

    ringtonemodifiedfilepathandtitle = BASE_DIR + '/ringtonemodifiedfiles/' + ectoken + '/' + ringtonemasterfiletitle + '_wwwdotaiddotcom_cor' + str(
        cornumber) + '.mp3'
    file = open(ringtonemodifiedfilepathandtitle, 'wb')
    file.write(ringtonemasterfilecontent)
    file.close()

    ringtonemodifiedfiletitle = ringtonemasterfiletitle + '_wwwdotaiddotcom_cor' + str(
        cornumber) + '.mp3'
    # making ringtonemodifiedfilewithtitle end

    # preparing ringtonemodifiedfile to send end

    subject = 'Your ringtone file from Aid'
    message = render_to_string('aid/aringtonemodifiedfilesendingemail.html', {
        'payerfirstname': payerfirstname,
    })
    email = EmailMessage(subject, message, '*****@*****.**',
                         [emailtosend])  # , cc=[cc])
    email.attach_file(ringtonemodifiedfilepathandtitle)
    email.content_subtype = "html"
    email.send()

    return render(
        request, 'aid/aorderprocessringtoneorderthankyouredirecturl.html', {
            'emailtosend': emailtosend,
            'cordocid': cordocid,
            'ringtonemodifiedfiletitle': ringtonemodifiedfiletitle
        })
Beispiel #56
0
 def render_mail(self, subject, template_name, email, context):
     from_email = settings.DEFAULT_FROM_EMAIL
     body = render_to_string(template_name, context).strip()
     msg = EmailMessage(subject, body, from_email, [email])
     msg.content_subtype = 'html'  # Main content is now text/html
     return msg
Beispiel #57
0
def adocorderadd(request):
    if request.method == "POST":
        qty2 = request.POST['qty2']
        creatorid = request.user.id
        #        import pdb;
        #        pdb.set_trace()

        cursor1 = connection.cursor()
        cursor1.execute(
            "SELECT contactid_tblacontacts, "
            "companyname_tblacompanies, "
            "Companyid_tblaCompanies, "
            "Firstname_tblacontacts, "
            "lastname_tblacontacts, "
            "title_tblacontacts, "
            "mobile_tblacontacts, "
            "email_tblacontacts, "
            "pcd_tblacompanies, "
            "town_tblacompanies, "
            "address_tblacompanies "
            "FROM aid_tblacontacts "
            "JOIN aid_tblacompanies "
            "ON aid_tblacompanies.companyid_tblacompanies = aid_tblacontacts.companyid_tblacontacts_id "
            "WHERE contactid_tblacontacts =%s", [13])
        companyandcontactdata = cursor1.fetchall()

        for instancesingle in companyandcontactdata:
            companynameclone = instancesingle[1]

            companyid = instancesingle[
                2]  # for the lookup the default values in the tblcompanies (i.e. defaultpreface)
            firstnameclone = instancesingle[3]
            lastnameclone = instancesingle[4]
            titleclone = instancesingle[5]
            mobileclone = instancesingle[6]
            emailclone = instancesingle[7]
            pcdclone = instancesingle[8]
            townclone = instancesingle[9]
            addressclone = instancesingle[10]
        cursor5 = connection.cursor()
        cursor5.execute(
            "SELECT defaultbackpageidforquotation_tblcompanies, "
            "defaultprefaceidforquotation_tblcompanies, "
            "defaultpaymentid_tblcompanies "
            "FROM quotation_tblcompanies "
            "WHERE Companyid_tblCompanies = %s", [companyid])
        defaultsfromtblcompanies = cursor5.fetchall()
        for instancesingle in defaultsfromtblcompanies:
            defaultbackpageidforquotation = instancesingle[0]
            defaultprefaceidforquotation = instancesingle[1]
            defaultpaymentid = instancesingle[2]
        cursor6 = connection.cursor()
        cursor6.execute(
            "SELECT paymenttextforquotation_tblpayment "
            "FROM quotation_tblpayment "
            "WHERE paymentid_tblpayment = %s", [defaultpaymentid])
        paymentset = cursor6.fetchall()
        for instancesingle in paymentset:
            paymenttextcloneforquotation = instancesingle[0]
        cursor6 = connection.cursor()
        cursor6.execute(
            "SELECT backpagetextforquotation_tblbackpageforquotation "
            "FROM quotation_tblbackpageforquotation "
            "WHERE backpageidforquotation_tblbackpageforquotation = %s",
            [defaultbackpageidforquotation])
        backpageset = cursor6.fetchall()
        for instancesingle in backpageset:
            backpagetextcloneforquotation = instancesingle[0]
        cursor7 = connection.cursor()
        cursor7.execute(
            "SELECT prefacetextforquotation_tblprefaceforquotation "
            "FROM quotation_tblprefaceforquotation "
            "WHERE prefaceidforquotation_tblprefaceforquotation = %s",
            [defaultprefaceidforquotation])
        prefaceset = cursor7.fetchall()
        for instancesingle in prefaceset:
            prefacecloneforquotation = instancesingle[0]
        cursor7 = connection.cursor()
        cursor7.execute("SELECT currencyisocode_tblcurrency "
                        "FROM quotation_tblcurrency "
                        "WHERE accountcurrency_tblcurrency = 1")
        results = cursor7.fetchall()
        for instancesingle in results:
            accountcurrencycodeclone = instancesingle[0]

        cursor8 = connection.cursor()
        cursor8.execute(
            "SELECT max(docnumber_tblaDoc) FROM aid_tbladoc "
            "WHERE Doc_kindid_tblaDoc_id = %s", ['2'])
        results = cursor8.fetchall()
        resultslen = len(results)
        # import pdb;
        # pdb.set_trace()

        if results[0][
                0] is not None:  # only if there is not doc yet (this would be the first instance)
            for x in results:
                docnumber = x[0]
                docnumber += 1
        else:
            docnumber = 80  # arbitrary number

        cursor2 = connection.cursor()
        cursor2.execute(
            "INSERT INTO aid_tbladoc "
            "( Doc_kindid_tblaDoc_id, "
            "Contactid_tblaDoc_id,"
            "companyname_tblcompanies_ctbladoc, "
            "firstname_tblcontacts_ctbladoc, "
            "lastname_tblcontacts_ctbladoc, "
            "prefacetextforquotation_tblprefaceforquotation_ctbladoc, "
            "backpagetextforquotation_tblbackpageforquotation_ctbladoc, "
            "docnumber_tblaDoc, "
            "creatorid_tbladoc, "
            "title_tblcontacts_ctbladoc, "
            "mobile_tblcontacts_ctbladoc, "
            "email_tblcontacts_ctbladoc, "
            "pcd_tblcompanies_ctbladoc, "
            "town_tblcompanies_ctbladoc, "
            "address_tblcompanies_ctbladoc, "
            "paymenttextforquotation_tblpayment_ctbladoc, "
            "accountcurrencycode_tbladoc) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
            [
                '2', '1', companynameclone, firstnameclone, lastnameclone,
                prefacecloneforquotation, backpagetextcloneforquotation,
                docnumber, creatorid, titleclone, mobileclone, emailclone,
                pcdclone, townclone, addressclone,
                paymenttextcloneforquotation, accountcurrencycodeclone
            ])

        cursor3 = connection.cursor()
        cursor3.execute("SELECT max(Docid_tblaDoc) " "" "FROM aid_tbladoc")
        results = cursor3.fetchall()
        for x in results:
            maxdocid = x[0]

        cursor3 = connection.cursor()
        cursor3.execute(
            "SELECT "
            "Doc_kindid_tblaDoc_id, "
            "docnumber_tblaDoc, "
            "pretag_tbladockind "
            "FROM aid_tbladoc "
            "JOIN aid_tbladoc_kind as DK "
            "ON Doc_kindid_tblaDoc_id = DK.Doc_kindid_tblaDoc_kind "
            "WHERE docid_tbladoc=%s ", [maxdocid])
        customerordernumbers = cursor3.fetchall()
        for x in customerordernumbers:
            customerordernumberdocnumber = x[1]
            customerordernumberpretag = x[2]
        customerordernumber = str(customerordernumberpretag) + str(
            customerordernumberdocnumber)
        #product variables filling begin
        cursor0 = connection.cursor()
        cursor0.execute(
            "SELECT `Productid_tblaProduct`, "
            "`purchase_price_tblaproduct`, `"
            "customerdescription_tblaProduct`, "
            "`margin_tblaproduct`, "
            "`currencyisocode_tblcurrency_ctblaproduct`, "
            "currencyrate_tblacurrency, "
            "unit_tblaproduct, "
            "supplierdescription_tblaProduct, "
            "suppliercompanyid_tblaProduct "
            "FROM `aid_tblaproduct` "
            "LEFT JOIN aid_tblacurrency "
            "ON aid_tblaproduct.currencyisocode_tblcurrency_ctblaproduct=aid_tblacurrency.currencyisocode_tblacurrency "
            "WHERE Productid_tblaProduct= %s", ['2'])
        results = cursor0.fetchall()
        for instancesingle in results:
            purchase_priceclone = instancesingle[1]
            customerdescriptionclone = instancesingle[2]
            currencyisocodeclone = instancesingle[4]
            marginfromproducttable = instancesingle[3]
            listpricecomputed = round(
                (100 * purchase_priceclone) / (100 - marginfromproducttable),
                2)
            currencyrateclone = instancesingle[5]
            unitclone = instancesingle[6]
            supplierdescriptionclone = instancesingle[7]
            suppliercompanyidclone = instancesingle[8]

            unitsalespriceACU = listpricecomputed * currencyrateclone
        # import pdb;
        # pdb.set_trace()


# product variables filling end
# product row to docdetails begin
        cursor1 = connection.cursor()  # new row needed
        cursor1.execute(
            "INSERT INTO aid_tbladoc_details "
            "(`Qty_tblaDoc_details`, "
            "`Docid_tblaDoc_details_id`, "
            "`Productid_tblaDoc_details_id`, "
            "`firstnum_tblaDoc_details`, "
            "`fourthnum_tblaDoc_details`, "
            "`secondnum_tblaDoc_details`, "
            "`thirdnum_tblaDoc_details`, "
            "`Note_tblaDoc_details`, "
            "`purchase_price_tblproduct_ctblaDoc_details`, "
            "`customerdescription_tblProduct_ctblaDoc_details`, "
            "`currencyisocode_tblcurrency_ctblproduct_ctblaDoc_details`, "
            "listprice_tblaDoc_details, "
            "currencyrate_tblcurrency_ctblaDoc_details, "
            "unitsalespriceACU_tblaDoc_details, "
            "unit_tbladocdetails, "
            "`supplierdescription_tblProduct_ctblaDoc_details`, "
            "suppliercompanyid_tblaDocdetails) "
            "VALUES (%s, %s, %s, %s,%s,%s,%s,'Defaultnote', %s, %s, %s, %s, %s, %s, %s, %s, %s)",
            [
                qty2, maxdocid, '2', '1', '1', '1', '1', purchase_priceclone,
                customerdescriptionclone, currencyisocodeclone,
                listpricecomputed, currencyrateclone, unitsalespriceACU,
                unitclone, supplierdescriptionclone, suppliercompanyidclone
            ])
        # product row to docdetails end
        # email acknowledgement begin
        foo = 11
        html_message = render_to_string(
            'aid/acustomeracknowledgementemail.html', {
                'context': 'values',
                'customerordernumber': customerordernumber
            })
        email = EmailMessage('Aid Order Acknowledgement', html_message,
                             '*****@*****.**',
                             ['*****@*****.**'])  # , cc=[cc])
        email.content_subtype = "html"
        email.send()

        # email acknowledgement end

        return redirect('adocselector', pk=maxdocid)

    cursor0 = connection.cursor()
    cursor0.execute(
        "SELECT aid_tblacontacts.contactid_tblacontacts, aid_tblacompanies.companyname_tblacompanies,"
        "aid_tblacontacts.Firstname_tblacontacts, aid_tblacontacts.lastname_tblacontacts "
        "FROM aid_tblacontacts "
        "JOIN aid_tblacompanies "
        "ON aid_tblacompanies.companyid_tblacompanies = aid_tblacontacts.companyid_tblacontacts_id "
        "ORDER BY companyname_tblacompanies")
    contacts = cursor0.fetchall()
    transaction.commit()

    cursor = connection.cursor()
    cursor.execute(
        "SELECT doc_kindid_tbldoc_kind, doc_kind_name_tbldoc_kind FROM quotation_tbldoc_kind"
    )
    dockinds = cursor.fetchall()
    transaction.commit()

    return render(request, 'aid/adocadd.html', {
        'dockinds': dockinds,
        'contacts': contacts
    })
Beispiel #58
0
def register(request):
    if request.method == "POST":
        form_u = UserRegisterForm(request.POST)
        form_c = CollegeForm(request.POST)
        if form_u.is_valid() and form_c.is_valid():
            new_user = form_u.save()

            new_obj = form_c.save(commit=False)
            new_obj.user = new_user
            new_obj.save()

            new_obj1 = Students(college=new_obj,
                                participant_name=request.POST['participant1'],
                                gender=request.POST['gender1'])
            new_obj1.save()
            new_obj2 = Students(college=new_obj,
                                participant_name=request.POST['participant2'],
                                gender=request.POST['gender2'])
            new_obj2.save()
            new_obj3 = Students(college=new_obj,
                                participant_name=request.POST['participant3'],
                                gender=request.POST['gender3'])
            new_obj3.save()
            new_obj4 = Students(college=new_obj,
                                participant_name=request.POST['participant4'],
                                gender=request.POST['gender4'])
            new_obj4.save()
            new_obj5 = Students(college=new_obj,
                                participant_name=request.POST['participant5'],
                                gender=request.POST['gender5'])
            new_obj5.save()

            username = form_u.cleaned_data.get('username')
            messages.success(request, 'Account created for ' + username)
            email = request.POST['email']

            msg = EmailMessage(
                'Registration Successful for Nakshastra 2k19 NITC',
                "<html><h3>You have successfully registered for <b>Nakshatra 2k19</b></h3><br><h4>User Name: "
                + request.POST['username'] + "</h4><br>Participant 1: " +
                request.POST['participant1'] + "<br>Participant 2: " +
                request.POST['participant2'] + "<br>Participant 3: " +
                request.POST['participant3'] + "<br>Participant 4: " +
                request.POST['participant4'] + "<br>Participant 5: " +
                request.POST['participant5'] +
                "<br> <h4>Please make sure that you get the documents attached below. Also make sure to go through the rules thoroughly before attending the fest.</h4><br><h4>Contact Us at [email protected]</h4><br><h4>Coordinator - Harshit Garg : 7838146755 </h4><br><h4>PR - Rashi : 7902981382  </h4><br><h4>Shashidhar : 9177304519  </h4><br><h4>Nakshatra 2k19</h4>  </html>",
                '*****@*****.**',
                [email, '*****@*****.**'],
            )
            msg.content_subtype = "html"
            PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
            print('path:', PROJECT_ROOT)
            msg.attach_file(
                '/home/oceanknr/webapps/demo_django/myproject/pdfs/Confirmation_Mail.pdf'
            )
            msg.attach_file(
                '/home/oceanknr/webapps/demo_django/myproject/pdfs/rules.pdf')
            # msg.attach_file('pdfs/Confirmation_Mail.pdf')
            # msg.attach_file('pdfs/rules.pdf')

            msg.send()
            return redirect('login')
    else:
        form_u = UserRegisterForm()
        form_c = CollegeForm()
    return render(request, 'users/register.html', {
        'form_u': form_u,
        'form_c': form_c
    })
Beispiel #59
0
def mail(request):
    if request.GET.get("Command") == "GetEmail":
        email = request.GET.get("email")
        usr = request.GET.get("usr")
        message = request.GET.get("message")
        data = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Demystifying Email Design</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<body>
<style>
* {box-sizing: border-box;}
body {background: #FFF2E3;}
.wedding {
  position: relative;
  max-width: 350px;
  margin: 50px auto 0;
  text-align: center;
}
.form-inner:before {
  display: inline-block;
  margin-top: -45px;
  content: url(https://html5book.ru/wp-content/uploads/2017/05/form-flower.png);
}
.form-inner {
  padding: 0 40px 10px;
  margin-top: 45px;
  background: #ffffff;
  border-radius: 2px;
  box-shadow: 0 0 6px 1px rgba(0,0,0,.1);
}
.form-inner h2 {
  font-weight: 300;
  font-size: 20px;
  text-transform: uppercase;
  font-family: 'Cormorant Garamond', serif;
}
.form-content {
  position: relative;
  margin: 30px -40px 0 -40px;
  padding: 10px 40px 0 40px;
  background: #FFF8F3;
}
.form-content:before {
  content: "";
  position: absolute;
  top: -4px;
  right: 0;
  left: 0;
  height: 2px;
  border-top: 1px solid #DDDDDD;
  border-bottom: 1px solid #DDDDDD;
}
.form-content h3 {
  font-family: 'Marck Script', cursive;
  font-size: 22px;
  color: #898989;
  font-weight: normal;
}
.form-content input,
.form-content select {
  height: 38px;
  line-height: 38px;
  padding: 0 10px;
  background: #ffffff;
  border: 1px solid #DDDDDD;
  font-size: 20px;
  font-family: 'Cormorant Garamond', serif;
  color: #808080;
  outline: none;
}
.form-content input {width: 100%;}
.form-content input:focus,
.form-content select:focus {border-color: #C44D58;}
.form-content input[type="submit"] {
  margin: 20px 0;
  padding: 0 10px;
  background: #FF6B6B;
  color: #ffffff;   
  font-size: 18px;
  text-transform: uppercase;
  border-width: 0;
  border-radius: 20px;
  cursor: pointer;
  transition: .2s linear}
.form-content input[type="submit"]:hover {background: #C44D58;}
</style>
<form class="wedding">
  <div class="form-inner">
    <h2>От пользователей<br><h2>
    <div class="form-content">
      <h3>Почта отправителя: ''' + str(email) + '''</h3>
      <h3>Имя отправителя: ''' + str(usr) + '''</h3>
	  <h3>Его текст: ''' + str(message) + '''</h3> 
    </div>
  </div>
</form>
</body>
</head>
</html>'''
        email1 = EmailMessage('Служебка', data, to=['*****@*****.**'])
        email1.content_subtype = "html"
        email1.send()
        return HttpResponse("Fu")
Beispiel #60
0
def deploy(member):
    app = Application.objects.get(slug=DARAJA)
    daraja_service = Service.objects.get(project_name_slug=DARAJA)
    project_name_slug = slugify(member.username)
    ikwen_name = project_name_slug.replace('-', '')
    pname = ikwen_name
    i = 0
    while True:
        try:
            Service.objects.using(UMBRELLA).get(project_name_slug=pname)
            i += 1
            pname = "%s%d" % (ikwen_name, i)
        except Service.DoesNotExist:
            ikwen_name = pname
            break
    api_signature = generate_random_key(30, alpha_num=True)
    while True:
        try:
            Service.objects.using(UMBRELLA).get(api_signature=api_signature)
            api_signature = generate_random_key(30)
        except Service.DoesNotExist:
            break
    database = ikwen_name
    domain = 'go.' + pname + '.ikwen.com'
    now = datetime.now()
    expiry = now + timedelta(days=15)

    service = Service(member=member,
                      app=app,
                      project_name=member.full_name,
                      project_name_slug=ikwen_name,
                      domain=domain,
                      database=database,
                      expiry=expiry,
                      monthly_cost=0,
                      version=Service.FREE,
                      api_signature=api_signature)
    service.save(using=UMBRELLA)
    logger.debug("Service %s successfully created" % pname)

    # Import template database and set it up
    db_folder = DARAJA_CLOUD_FOLDER + '000Tpl/DB/000Default'
    host = getattr(settings, 'DATABASES')['default'].get('HOST', '127.0.0.1')
    subprocess.call(
        ['mongorestore', '--host', host, '-d', database, db_folder])
    logger.debug("Database %s successfully created on host %s from %s." %
                 (database, host, db_folder))

    add_database_to_settings(database)

    for s in member.get_services():
        db = s.database
        add_database_to_settings(db)
        collaborates_on_fk_list = member.collaborates_on_fk_list + [
            daraja_service.id
        ]
        customer_on_fk_list = member.customer_on_fk_list + [daraja_service.id]
        Member.objects.using(db).filter(pk=member.id).update(
            collaborates_on_fk_list=collaborates_on_fk_list,
            customer_on_fk_list=customer_on_fk_list)

    member.collaborates_on_fk_list = collaborates_on_fk_list
    member.customer_on_fk_list = customer_on_fk_list

    member.is_iao = True
    member.save(using=UMBRELLA)

    member.is_bao = True
    member.is_staff = True
    member.is_superuser = True

    app.save(using=database)
    member.save(using=database)
    logger.debug("Member %s access rights successfully set for service %s" %
                 (member.username, pname))

    # Add member to SUDO Group
    obj_list, created = UserPermissionList.objects.using(
        database).get_or_create(user=member)
    obj_list.save(using=database)
    logger.debug("Member %s successfully added to sudo group for service: %s" %
                 (member.username, pname))
    config = Config(service=service,
                    cash_out_rate=DARAJA_IKWEN_SHARE_RATE,
                    currency_code='XAF',
                    currency_symbol='XAF',
                    decimal_precision=0,
                    company_name=ikwen_name,
                    contact_email=member.email,
                    contact_phone=member.phone,
                    sms_api_script_url=SMS_API_URL)
    config.save(using=UMBRELLA)
    service.save(using=database)

    # Send notification and Invoice to customer
    vendor = get_service_instance()
    add_event(vendor, SERVICE_DEPLOYED, member=member)
    sender = 'ikwen Daraja <*****@*****.**>'
    sudo_group = Group.objects.using(UMBRELLA).get(name=SUDO)
    add_event(vendor, SERVICE_DEPLOYED, group_id=sudo_group.id)
    subject = _("Welcome to the business network.")
    registered_company_list_url = vendor.url + reverse(
        'daraja:registered_company_list')
    html_content = get_mail_content(
        subject,
        template_name='daraja/mails/service_deployed.html',
        extra_context={
            'registered_company_list_url': registered_company_list_url,
            'member': member
        })
    msg = EmailMessage(subject, html_content, sender, [member.email])
    bcc = ['*****@*****.**']
    msg.bcc = list(set(bcc))
    msg.content_subtype = "html"
    Thread(target=lambda m: m.send(), args=(msg, )).start()
    logger.debug("Notice email submitted to %s" % member.email)
    return service