Beispiel #1
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertMessageHasHeaders(message, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable'),
            ('Subject', 'Subject'),
            ('From', '*****@*****.**'),
            ('To', '*****@*****.**')})
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        payload0 = msg.message().get_payload(0)
        self.assertMessageHasHeaders(payload0, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload0.as_string().endswith('\n\nFirstname S=FCrname is a great guy.'))
        payload1 = msg.message().get_payload(1)
        self.assertMessageHasHeaders(payload1, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/html; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload1.as_string().endswith('\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'))
Beispiel #2
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertMessageHasHeaders(message, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable'),
            ('Subject', 'Subject'),
            ('From', '*****@*****.**'),
            ('To', '*****@*****.**')})
        self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content, '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        payload0 = msg.message().get_payload(0)
        self.assertMessageHasHeaders(payload0, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/plain; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload0.as_bytes().endswith(b'\n\nFirstname S=FCrname is a great guy.'))
        payload1 = msg.message().get_payload(1)
        self.assertMessageHasHeaders(payload1, {
            ('MIME-Version', '1.0'),
            ('Content-Type', 'text/html; charset="iso-8859-1"'),
            ('Content-Transfer-Encoding', 'quoted-printable')})
        self.assertTrue(payload1.as_bytes().endswith(b'\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'))
Beispiel #3
0
def task_user_change_notify(sender, **kwargs):
    """
    Оповещение об измененях задачи.

    """
    task = sender
    email = task.user.email
    subject = _('You have an assigned task')
    headers = {
        'X-iifd-exmo': 'task_user_change_notification'
    }
    if Site._meta.installed:
        site = Site.objects.get_current()
        url = '%s://%s%s' % ('http', site, reverse('exmo2010:score_list_by_task', args=[task.pk]))
    else:
        url = None

    t = loader.get_template('task_user_changed.html')
    c = Context({'task': task, 'url': url, 'subject': subject})
    message = t.render(c)

    email = EmailMessage(subject, message, config_value('EmailServer', 'DEFAULT_FROM_EMAIL'), [email], headers=headers)
    email.encoding = "utf-8"
    email.content_subtype = "html"
    email.send()
Beispiel #4
0
def send_invoice(purchase_id, recipients):
    if not recipients:
        return

    from .models import Purchase

    try:
        purchase = Purchase.objects.get(pk=purchase_id)
    except Purchase.DoesNotExist:
        raise RuntimeError('No purchase found with pk %d' % purchase_id)

    if not purchase.exported:
        # Safe call 'cause exported will be set
        # if send_invoice is invoked again
        render_invoice.delay(purchase_id)
        raise RuntimeError('Invoked rendering of invoice pk %d' % purchase_id)

    subject = _('Your EuroPython 2014 Invoice %(full_invoice_number)s') % {
        'full_invoice_number': purchase.full_invoice_number,
    }
    message = render_to_string(
        'attendees/mail_payment_invoice.html', {
            'first_name': purchase.first_name,
            'last_name': purchase.last_name,
            'conference': purchase.conference,
        })
    msg = EmailMessage(subject, message, to=recipients)
    msg.encoding = 'utf-8'
    ext = '.json' if settings.INVOICE_DISABLE_RENDERING else '.pdf'
    filename = '%s%s' % (purchase.full_invoice_number, ext
                         )  # attachment filename
    with open(purchase.invoice_filepath, 'rb') as f:
        content = f.read()
    msg.attach(filename, content)
    msg.send()
Beispiel #5
0
def send_invoice(purchase_id, recipients):
    if not recipients:
        return

    from .models import Purchase

    try:
        purchase = Purchase.objects.get(pk=purchase_id)
    except Purchase.DoesNotExist:
        raise RuntimeError('No purchase found with pk %d' % purchase_id)

    if not purchase.exported:
        # Safe call 'cause exported will be set
        # if send_invoice is invoked again
        render_invoice.delay(purchase_id)
        raise RuntimeError('Invoked rendering of invoice pk %d' % purchase_id)

    subject = _('Your EuroPython 2014 Invoice %(full_invoice_number)s') % {
        'full_invoice_number': purchase.full_invoice_number,
    }
    message = render_to_string('attendees/mail_payment_invoice.txt', {
        'first_name': purchase.first_name,
        'last_name': purchase.last_name,
        'conference': purchase.conference,
    })
    msg = EmailMessage(subject, message, to=recipients)
    msg.encoding = 'utf-8'
    ext = '.json' if app_settings.INVOICE_DISABLE_RENDERING else '.pdf'
    filename = '%s%s' % (purchase.full_invoice_number, ext)  # attachment filename
    with open(purchase.invoice_filepath, 'rb') as f:
        content = f.read()
    msg.attach(filename, content)
    msg.send()
Beispiel #6
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage("Subject", "Firstname Sürname is a great guy.", "*****@*****.**", ["*****@*****.**"])
        email.encoding = "iso-8859-1"
        message = email.message()
        self.assertTrue(
            message.as_string().startswith(
                'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'
            )
        )
        self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = "Firstname Sürname is a great guy."
        html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
        msg = EmailMultiAlternatives("Subject", text_content, "*****@*****.**", ["*****@*****.**"])
        msg.encoding = "iso-8859-1"
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(
            msg.message().get_payload(0).as_string(),
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.',
        )
        self.assertEqual(
            msg.message().get_payload(1).as_string(),
            'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>',
        )
Beispiel #7
0
def schedule_notify_email(org, occurrence, occurrence_confirmation):
    """
        to nofity by email a careprofessional if occurrence presence is 4 or 5
    """
    to = []
    oc_list = []
    oc_list.append(occurrence)

    if occurrence_confirmation.presence == 4:
        title = _('Occurrence unmarked')
    if occurrence_confirmation.presence == 5:
        title = _('Occurrence rescheduled')

    # emails address of all professional
    for p in occurrence.event.referral.professional.all():
        if p.person.notify.all() and p.person.notify.get(org_id=org.id).change_event:
            for e in p.person.emails.all():
                if not e.email in to:
                    to.append(e.email)

    if to:
        # render template
        text = Context({'oc_list':oc_list, 'title':title, 'org':org, 'showdt':True})
        template = get_template("schedule/schedule_notify_careprofessional.html").render(text)
        # sendmail
        msg = EmailMessage()
        msg.subject = u"GestorPsi - %s" % title
        msg.content_subtype = 'html'
        msg.encoding = "utf-8"
        msg.body = template
        msg.to = to
        msg.send()
        return True

    return False
Beispiel #8
0
def send_attach_email(request,
                      email_list,
                      subject=None,
                      body=None,
                      file_path=None):
    if not subject:
        subject = u'【医咖会】-申请的资源文章已审核通过'
    else:
        subject = subject
    if not body:
        body = u'<p>附件是你申请的资源原文,请查收!</p>'
    else:
        body = body
    from_email = settings.EMAIL_HOST_USER
    recipient_list = email_list

    s_email = EmailMessage(subject=subject,
                           body=body,
                           from_email=from_email,
                           to=recipient_list)
    s_email.content_subtype = 'html'
    s_email.encoding = 'utf-8'
    if file_path:
        s_email.attach(filename=file_path.name,
                       content=file_path.read(),
                       mimetype='application/octet-stream;charset=utf-8')
    # s_email.send()

    if s_email.send():
        return True
    else:
        return False
Beispiel #9
0
    def test_encoding(self):
        """
        Regression for #12791 - Encode body correctly with other encodings
        than utf-8
        """
        email = EmailMessage('Subject', 'Firstname Sürname is a great guy.',
                             '*****@*****.**', ['*****@*****.**'])
        email.encoding = 'iso-8859-1'
        message = email.message()
        self.assertTrue(message.as_string().startswith(
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]'
        ))
        self.assertEqual(message.get_payload(),
                         'Firstname S=FCrname is a great guy.')

        # Make sure MIME attachments also works correctly with other encodings than utf-8
        text_content = 'Firstname Sürname is a great guy.'
        html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>'
        msg = EmailMultiAlternatives('Subject', text_content,
                                     '*****@*****.**', ['*****@*****.**'])
        msg.encoding = 'iso-8859-1'
        msg.attach_alternative(html_content, "text/html")
        self.assertEqual(
            msg.message().get_payload(0).as_string(),
            'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.'
        )
        self.assertEqual(
            msg.message().get_payload(1).as_string(),
            'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>'
        )
Beispiel #10
0
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator, from_email=None, request=None):
        """
        Sending emails with html content only.

        """
        for user in self.users_cache:
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override

            t = loader.get_template(email_template_name)

            c = Context({
                'email': user.email,
                'domain': domain,
                'site_name': site_name,
                'uid': int_to_base36(user.id),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': use_https and 'https' or 'http',
            })

            message = t.render(c)

            msg = EmailMessage(_("Password reset on %s") % site_name,
                               message,
                               config_value('EmailServer', 'DEFAULT_FROM_EMAIL'),
                               [user.email])
            msg.encoding = "utf-8"
            msg.content_subtype = "html"
            msg.send()
Beispiel #11
0
 def send_email(self, msg, recipient: str = '*****@*****.**'):
     """Отправка email сообщения
        Сообщение =>
        from email.mime.text import MIMEText
        from email.header import Header
        msg = MIMEText(text, 'plain', 'utf-8')
        msg['Subject'] = Header(self.name, 'utf-8')
        msg['From'] = account.email
        msg['To'] = ', '.join(recipients)"""
     if not self.email or not self.smtp_server or not self.smtp_port or not self.passwd:
         return
     msg['From'] = self.email
     msg['To'] = recipient
     # ---------------------------
     # Создаем бэкэнд для рассылки
     # ---------------------------
     conn = get_connection(
         host=self.smtp_server,
         port=self.smtp_port,
         username=self.email,
         password=self.passwd,
         use_tls=True,
     )
     mail = EmailMessage(msg['Subject'],
                         None,
                         msg['From'], [
                             msg['To'],
                         ],
                         connection=conn)
     mail.encoding = 'utf8'
     mail.attach(msg)  # Attach the raw MIMEBase descendant
     mail.send()
     """
Beispiel #12
0
    def get(self, request, pk, **kwargs):
        bill = Bill.objects.get(pk=pk)
        user_infor = bill.customer
        html = render_to_string('facturierApp/bill_detail.html', {
            'bill': bill,
            'pdf': True
        })
        pdf = HTML(string=html,
                   base_url='http://127.0.0.1:8000/quotation/' + str(bill.pk) +
                   '/').write_pdf()
        to_emails = [str(user_infor.email)]
        subject = "Bill " + user_infor.full_name()
        email = EmailMessage(subject,
                             from_email='*****@*****.**',
                             to=to_emails)

        email.attach("certificate_{}".format(user_infor.full_name()) + '.pdf',
                     pdf, "application/pdf")
        email.content_subtype = "pdf"  # Main content is now text/html

        print email
        email.encoding = 'us-ascii'
        email.send()

        return HttpResponseRedirect(reverse('bill_detail', args=[bill.pk]))
Beispiel #13
0
    def get(self, request, pk, **kwargs):

        quotation = Quotation.objects.get(pk=pk)
        user_infor = quotation.customer
        html = render_to_string('facturierApp/quotation_detail.html', {
            'quotation': quotation,
            'pdf': True
        })

        pdf = HTML(string=html,
                   base_url='http://127.0.0.1:8000/quotation/' +
                   str(quotation.pk) + '/').write_pdf(
                       stylesheets=[CSS(string='body { font-family: serif}')])

        to_emails = [
            str(user_infor.email),
        ]
        subject = "Quotation " + user_infor.full_name()
        email = EmailMessage(subject,
                             from_email='*****@*****.**',
                             to=to_emails)

        email.attach("certificate_{}".format(user_infor.full_name()) + '.pdf',
                     pdf, "application/pdf")
        email.content_subtype = "pdf"  # Main content is now text/html

        print email
        email.encoding = 'us-ascii'
        email.send()

        return HttpResponseRedirect(
            reverse('quotation_detail', args=[quotation.pk]))
Beispiel #14
0
def sendmail(request):
    settings = ContactData.getFullConfig()
    email = EmailMessage(request.POST['subject']+' FROM: '+request.POST['name'], request.POST['message'], settings['email'],
            reply_to=request.POST['email'], headers={'Content-Type': 'text/html', 'Message-ID': 'contact'})
    #email.content_subtype = "html"
    email.encoding = 'utf8'
    email.send()
    return HttpResponseRedirect('/')
Beispiel #15
0
def send_mail(
    request, recipients, subject, femail, template, data, bcc=None,
    content='html', attach=False
):

    if not bcc:
        bcc = [settings.MANAGERS[0][1],]

    t = loader.get_template(template)
    # VERSION returns (1, x, x, u'final', 1)
    # hopefully, we will be done using django 1.6 by the time 2.x comes out
    if django.VERSION[1] > 6:
        if request:
            rendered = t.render({'data':data,}, request)
        else:
            rendered = t.render({'data':data,},)
    else:
        if request:
            c = RequestContext(request, {'data':data,})
        else:
            c = Context({'data':data,})
        rendered = t.render(c)

    headers = {'Reply-To': femail,'From': femail,}

    email = EmailMessage(
        subject, rendered, femail, recipients, bcc, headers=headers
    )

    email.encoding = 'utf-8'

    if content:
        email.content_subtype = content

    if attach:
        try:
            email.attach_file(attach)
        except:
            for field, value in request.FILES.items():
                email.attach(value.name, value.read(), value.content_type)

    status = False
    # try 5 times then quit
    count = 0
    while True:
        try:
            email.send(fail_silently=False)
            status = True
            break
        except:
            count += 1
            if count < 5:
                pass
            else:
                break

    return status
Beispiel #16
0
def email_contract(request,id):
    if request.method == 'GET':
        customer_plan_data = CustomerServiceContract.objects.values(
            'id',
            'user_id',
            'customerwithservice',
            'type',
            'payment_status',
            'user_id__account_id',
            'user_id__first_name',
            'user_id__last_name',
            'user_id__email_address',
            'created_at',
            'contract_terms'
        ).filter(pk=id)
        address = AccountAddressCustomer.objects.values(
            'id',
            'user_id',
            'address_1',
            'address_2',
            'city__city_name',
            'province__province_name',
            'country__country_name'
            ).filter(user_id=customer_plan_data[0]['user_id'])

        subject = 'Contract of egciptv'

        n = random.randint(1000000, 9999999)

        service_plan = CustomerWithService.objects.values('id', 'service_plan_id__title', 'service_price_actual',
                                                          'service_plan_id',
                                                          'service_price_retail', 'service_price_qty',
                                                          'plan_status').filter(
            user_id=customer_plan_data[0]['user_id'])

        service_plan_hardware = ServicePlanWithHardware.objects.values('id', 'hw_id', 'hw_qty', 'hw_status',
                                                                       'hw_id__hw_title').filter(
            service_plan_id=service_plan[0]['service_plan_id'])

        # file_path = path.relpath("r/download.pdf")
        # f = open(file_path, 'w+')
        # ty = render_to_string('admin/customer/contract/mail/contract_attch.html')
        # f.write(ty)
        # f.close()

        pdf = render_to_string('admin/customer/contract/mail/email.html')
        file_path = path.relpath("r/contract.pdf")
        fd = open(file_path, 'rb')
        msg = EmailMessage(subject,pdf,'*****@*****.**', to=[request.GET['emailto']])
        msg.attach("contract.pdf", fd.read(), 'application/pdf')
        msg.content_subtype = "html"
        msg.encoding = 'utf-8'
        msg.send()

        id = request.session['customer']
        messages.add_message(request, messages.SUCCESS, 'Mail Resend')
        return HttpResponseRedirect(reverse('customer_details', kwargs={'id': id}))
Beispiel #17
0
def user_favorites():
    favorites = Favourite.objects.filter(active=1).order_by('user')
    csvfile=StringIO.StringIO()
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['User Number', 'business name'])
    for i, b in enumerate(favorites):
        csv_writer.writerow([b.user.number, b.business.name])

    message = EmailMessage('User Favorites - Haptik', 'Business favorites by User', '*****@*****.**' , EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('haptik_favorites.csv' , csvfile.getvalue(), 'text/csv')
    message.send()
def send_email_notification(sender, instance, **kwargs):
    if kwargs['created']:
        try:
            contest = instance.contest
            emails = contest.moderator_emails.split()
            if len(emails) > 0:
                body = render_to_string('%s/%s' % (settings.TEMPLATE_THEME, 'contest/email_notification.html'), {'work': instance})
                msg = EmailMessage(u"Новая работа на конкурс %s" % contest.title, body, settings.FROM_EMAIL, emails)
                msg.content_subtype = "html"
                msg.encoding = "UTF-8"
                msg.send(fail_silently=True)
        except:
            pass
Beispiel #19
0
def website_signup_csv():
    signups = WebsiteSignups.objects.all() 
    #with open('website_signup.csv' , 'w') as csvfile:
    csvfile=StringIO.StringIO()
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['No.', 'country_code', 'number', 'singedup on'])
    for i, b in enumerate(signups):
        csv_writer.writerow([i+1, b.country_code.strip(), b.number.strip(), b.created_at])

    message = EmailMessage('Website Signups - Haptik', 'Website Signups', '*****@*****.**' , EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('singups.csv' , csvfile.getvalue(), 'text/csv')
    #message.attach_file('/home/ubuntu/haptik_api/website_signup.csv')
    message.send()
Beispiel #20
0
def sql_execute(request, sqlid, token, uid):
    user = request.user
    try:
        sqlid = force_text(urlsafe_base64_decode(sqlid))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        sqlid = None
    if user is not None and account_activation_token.check_token(user, token):
        # TODO - dlaczego sqlid jest zly? Likwidacja sztywniaka
        # Trimming because __str__ for Query strings add [' ']
        sqlcmd = str(SQLCommand.objects.filter(id=21).values_list('command', flat=True))[2:][:-2]

        # Run query.
        # TODO - how to avoid sql injection ?
        cursor = connection.cursor()
        cursor.execute(sqlcmd)
        data = cursor.fetchall()

        # generate filename for storing
        filename = "sqloutput_" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        filename += '.csv'

        # store output in server as csv file. Location is not accessible to public.
        store_as_csv(data,filename,settings.CSV_ROOT)
        #return HttpResponse(filename)

        full_filepath = settings.CSV_ROOT + os.path.sep + filename
        # Check if file has been created and send if
        if os.path.exists(full_filepath):
            mail_subject = 'Output from sql'
            message = render_to_string('sql_executed.html', {
                'user': request.user.username
            })
            to_email = str(User.objects.filter(pk=force_text(urlsafe_base64_decode(uid))).values_list('email', flat=True))[2:][:-2]
            #return HttpResponse(to_email)
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.encoding = "utf-8"
            file = open(full_filepath, "r")
            email.attach(full_filepath, content = file.read(), mimetype="text/csv")
            file.close()
            email.send()
        else:
            return HttpResponse('Something wrong with generating csv filename with response!')

        return HttpResponse('SQL command succesfully generated and send to requestor.')
    else:
        return HttpResponse('Activation link for sql command is not valid!')
Beispiel #21
0
def score_change_notify(sender, **kwargs):
    """
    Оповещение об измененях оценки.

    """
    form = kwargs["form"]
    score = form.instance
    request = kwargs["request"]
    changes = []
    if form.changed_data:
        for change in form.changed_data:
            change_dict = {
                "field": change,
                "was": form.initial.get(change, form.fields[change].initial),
                "now": form.cleaned_data[change],
            }
            changes.append(change_dict)
    if score.task.approved:
        rcpt = []
        for profile in UserProfile.objects.filter(organization=score.task.organization):
            if (
                profile.user.is_active
                and profile.user.email
                and profile.notify_score_preference["type"] == UserProfile.NOTIFICATION_TYPE_ONEBYONE
            ):
                rcpt.append(profile.user.email)
        rcpt = list(set(rcpt))
        subject = _("%(prefix)s%(monitoring)s - %(org)s: %(code)s - Score changed") % {
            "prefix": config_value("EmailServer", "EMAIL_SUBJECT_PREFIX"),
            "monitoring": score.task.organization.monitoring,
            "org": score.task.organization.name.split(":")[0],
            "code": score.parameter.code,
        }
        headers = {"X-iifd-exmo": "score_changed_notification"}
        url = "%s://%s%s" % (
            request.is_secure() and "https" or "http",
            request.get_host(),
            reverse("exmo2010:score_view", args=[score.pk]),
        )
        t = loader.get_template("score_email.html")
        c = Context({"score": score, "url": url, "changes": changes, "subject": subject})
        message = t.render(c)
        for rcpt_ in rcpt:
            email = EmailMessage(
                subject, message, config_value("EmailServer", "DEFAULT_FROM_EMAIL"), [rcpt_], headers=headers
            )
            email.encoding = "utf-8"
            email.content_subtype = "html"
            email.send()
Beispiel #22
0
def beta_distrib_csv():
    beta_distrib = BetaDistrib.objects.all()
    csvfile=StringIO.StringIO()
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['No.', 'number', 'Opened'])
    for i, b in enumerate(beta_distrib):
        opened = 'No' 
        if not b.active:
            opened = 'Yes'
        csv_writer.writerow([i+1, b.number.strip(), opened])

    message = EmailMessage('Beta Links sent - Haptik', 'Beta Links Sent', '*****@*****.**' ,EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('beta_singups.csv' , csvfile.getvalue(), 'text/csv')
    message.send()
Beispiel #23
0
def haptik_users():
    users = User.objects.all()
    csvfile=StringIO.StringIO()
    csv_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['Id', 'country code', 'number', 'name'])
    for i, b in enumerate(users):
        name_fil = None
        if b.first_name:
            name = b.first_name
            name_fil = filter(lambda x: x in string.printable, name)
        csv_writer.writerow([b.id, b.country_code.strip(), b.number.strip(), name_fil])

    message = EmailMessage('Users - Haptik', 'All current Haptik Users', '*****@*****.**' , EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('haptik_users.csv' , csvfile.getvalue(), 'text/csv')
    message.send()
def enviar_correos(pdf, asunto, mensaje, correo, titulo):

    email_remitente = "*****@*****.**"
    if type(correo) == list:
        #print("entre a lista")
        email = EmailMessage(asunto, mensaje, email_remitente, correo)
    else:
        #print("entre variable")
        email = EmailMessage(asunto, mensaje, email_remitente, [
            correo,
        ])

    email.attach(titulo, pdf.getvalue(), "application/pdf")
    email.content_subtype = pdf  # Main content is now text/html
    email.encoding = 'ISO-8859-1'
    email.send()
Beispiel #25
0
def user_favorites():
    favorites = Favourite.objects.filter(active=1).order_by('user')
    csvfile = StringIO.StringIO()
    csv_writer = csv.writer(csvfile,
                            delimiter=',',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['User Number', 'business name'])
    for i, b in enumerate(favorites):
        csv_writer.writerow([b.user.number, b.business.name])

    message = EmailMessage('User Favorites - Haptik',
                           'Business favorites by User', '*****@*****.**',
                           EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('haptik_favorites.csv', csvfile.getvalue(), 'text/csv')
    message.send()
Beispiel #26
0
def send_pdf(request, pk):

    quotation = Quotation.objects.get(id=pk)
    print quotation, type(quotation)
    context = {'quotation': quotation}
    context['total'] = 0

    lines = QuotationLine.objects.filter(quotation=pk)

    for line in lines:
        context['total'] += line.quantity * line.product.price

    context['ttc'] = context['total'] * 20.6
    # print context, type(context)

    html = render_to_string('main_app/quotation_detail_pdf.html', context)
    # print html

    filename = 'quotation_' + pk + '_' + quotation.customer.first_name + '_' + quotation.customer.last_name + '.pdf'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=' + filename
    # print response

    pdf = HTML(string=html).write_pdf(
        stylesheets=[CSS(string='body { font-family: serif}')])

    to_emails = [quotation.customer.email]

    subject = "French-E Quotation du :" + quotation.date.strftime(
        '%Y-%m-%d %H:%M')

    email = EmailMessage(subject,
                         body=pdf,
                         from_email=settings.EMAIL_HOST_USER,
                         to=to_emails)

    email.attach(response['Content-Disposition'], pdf, "application/pdf")

    email.content_subtype = "pdf"  # Main content is now text/html
    email.encoding = 'us-ascii'
    email.send()

    return HttpResponse(pdf, content_type='application/pdf')
Beispiel #27
0
    def __call__(self, purchase):
        from . import utils

        if not self.recipients:
            LOG.warn("No recipients specified. Order won't be exported!")
            return
        json_data = self._purchase_to_json(purchase)
        order_number = utils.get_purchase_number(purchase)
        msg = EmailMessage(
            settings.PURCHASE_EXPORT_SUBJECT.format(purchase_number=order_number),
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=self.recipients,
            headers={"X-Data-Checksum": self._create_checksum(json_data)},
        )
        msg.encoding = "utf-8"
        msg.attach("data-{0}.json".format(order_number), json_data, "application/json")
        msg.send()
        purchase.exported = True
        purchase.save()
Beispiel #28
0
def beta_distrib_csv():
    beta_distrib = BetaDistrib.objects.all()
    csvfile = StringIO.StringIO()
    csv_writer = csv.writer(csvfile,
                            delimiter=',',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['No.', 'number', 'Opened'])
    for i, b in enumerate(beta_distrib):
        opened = 'No'
        if not b.active:
            opened = 'Yes'
        csv_writer.writerow([i + 1, b.number.strip(), opened])

    message = EmailMessage('Beta Links sent - Haptik', 'Beta Links Sent',
                           '*****@*****.**', EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('beta_singups.csv', csvfile.getvalue(), 'text/csv')
    message.send()
Beispiel #29
0
 def __call__(self, purchase):
     from . import utils
     if not self.recipients:
         LOG.warn("No recipients specified. Order won't be exported!")
         return
     json_data = self._purchase_to_json(purchase)
     order_number = utils.get_purchase_number(purchase)
     msg = EmailMessage(
         settings.PURCHASE_EXPORT_SUBJECT.format(
             purchase_number=order_number),
         from_email=settings.DEFAULT_FROM_EMAIL, to=self.recipients,
         headers={
             'X-Data-Checksum': self._create_checksum(json_data)
         })
     msg.encoding = 'utf-8'
     msg.attach('data-{0}.json'.format(order_number), json_data, 'application/json')
     msg.send()
     purchase.exported = True
     purchase.save()
    def form_valid(self, form):
        # print(form.cleaned_data)

        obj = form.save(commit=False)
        obj.managersign = form.cleaned_data['managersign_data']

        obj.save()

        engineersignb = Engineer.objects.get(id=obj.id).engineersign
        CUSTOMER = Engineer.objects.get(id=obj.id).CUSTOMER
        STORE = Engineer.objects.get(id=obj.id).STORE
        STORE_NO = Engineer.objects.get(id=obj.id).STORE_NO
        CALL_OUT_NO = Engineer.objects.get(id=obj.id).CALL_OUT_NO

        managersign = Engineer.objects.get(id=obj.id).managersign

        dataaa = {
            "engineersign": engineersignb,
            "CUSTOMER": CUSTOMER,
            'STORE': STORE,
            "STORE_NO": STORE_NO,
            "CALL_OUT_NO": CALL_OUT_NO,
            'managersign': managersign,
        }

        html = render_to_string('pdf/invoice.html', dataaa)
        pdf = weasyprint.HTML(string=html).write_pdf()

        to_emails = ['*****@*****.**']
        subject = "Certificate from " + STORE
        message = "Report Approved"
        email = EmailMessage(subject,
                             body=message,
                             from_email=settings.EMAIL_HOST_USER,
                             to=to_emails)
        email.attach("certificate.pdf", pdf, "application/pdf")
        email.content_subtype = "html"  # Main content is now text/html
        email.encoding = 'us-ascii'
        email.send()

        renderpdf = render_to_pdf('pdf/invoice.html', dataaa)
        return HttpResponse(renderpdf, content_type='application/pdf')
Beispiel #31
0
    def handle(self, *args, **options):
        movie_rent = MovieRent.objects.all()
        for movie in movie_rent : 
            rented_date = movie.checkout_date
            estimate_date = rented_date + datetime.timedelta(14)
            now = timezone.now()

            if estimate_date < now : 
                print 'you got time'
            else :
                customer_email = movie.customer.user.email
                from_email = '*****@*****.**'
                to_emails = [customer_email,]
                subject = "Codi'n Camp"
                message = 'rend moi mon film'


                email = EmailMessage(subject, message, from_email, to_emails)
                email.encoding = 'us-ascii'
                print email
Beispiel #32
0
def website_signup_csv():
    signups = WebsiteSignups.objects.all()
    #with open('website_signup.csv' , 'w') as csvfile:
    csvfile = StringIO.StringIO()
    csv_writer = csv.writer(csvfile,
                            delimiter=',',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['No.', 'country_code', 'number', 'singedup on'])
    for i, b in enumerate(signups):
        csv_writer.writerow(
            [i + 1,
             b.country_code.strip(),
             b.number.strip(), b.created_at])

    message = EmailMessage('Website Signups - Haptik', 'Website Signups',
                           '*****@*****.**', EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('singups.csv', csvfile.getvalue(), 'text/csv')
    #message.attach_file('/home/ubuntu/haptik_api/website_signup.csv')
    message.send()
Beispiel #33
0
def show_me_the_money(sender, **kwargs):
    ipn_obj = sender
    # Undertake some action depending upon `ipn_obj`.
    if ipn_obj.payment_status == ST_PP_COMPLETED:
        print('Payment is completed')
        user_infor = ast.literal_eval(ipn_obj.custom)
        if ipn_obj.receiver_email == settings.PAYPAL_RECEIVER_EMAIL:
            print('And Payment is valid')
            # generate and send an email with pdf certificate file to the user's email
            user_infor = ast.literal_eval(ipn_obj.custom)
            user_info = {
                "name": user_infor['name'],
                "hours": user_infor['hours'],
                "taggedArticles": user_infor['taggedArticles'],
                "email": user_infor['email'],
                "date": user_infor['date'],
            }
            html = render_to_string('users/certificate_template.html',
                                    {'user': user_info})
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'filename=certificate_{}'.format(
                user_info['name']) + '.pdf'
            pdf = weasyprint.HTML(
                string=html, base_url=settings.host +
                '/users/process/').write_pdf(stylesheets=[
                    weasyprint.CSS(string='body { font-family: serif}')
                ])
            to_emails = [str(user_infor['email'])]
            subject = "Certificate from Nami Montana"
            email = EmailMessage(subject,
                                 body=pdf,
                                 from_email=settings.EMAIL_HOST_USER,
                                 to=to_emails)
            email.attach("certificate_{}".format(user_infor['name']) + '.pdf',
                         pdf, "application/pdf")
            email.content_subtype = "pdf"  # Main content is now text/html
            email.encoding = 'us-ascii'
            email.send()
        else:
            payment_was_flagged.connect(do_not_show_me_the_money)
Beispiel #34
0
def schedule_notify_email(object=False):
    '''
        Sendmail to client after save event at schedule
        object = Occurrence()
    '''
    from django.template.loader import get_template
    from django.core.mail import EmailMessage
    from django.template import Context

    if object:
        to = []

        # emails address of client
        for c in object.event.referral.client.all():
            for e in c.person.emails.all():
                if not e.email in to:
                    to.append(e.email)

        # emaisl address of professional
        for c in object.event.referral.professional.all():
            for e in c.person.emails.all():
                if not e.email in to:
                    to.append(e.email)

        if to:
            text = Context({'client': object.event.referral.client.all()[0], 'professional': object.event.referral.professional.all()[0]})
            template = get_template("client/client_schedule_email.html").render(text)

            msg = EmailMessage()
            msg.subject = u"GestorPsi - Consulta marcada"
            msg.content_subtype = 'html'
            msg.encoding = "utf-8"
            msg.body = template
            msg.to = to
            msg.send()

            return True

    return False
    def form_valid(self, form, *args, **kwargs):
        obj = form.save()
        # print(obj.id)

        engineersign = Engineer.objects.get(id=obj.id).engineersign
        CUSTOMER = Engineer.objects.get(id=obj.id).CUSTOMER
        STORE = Engineer.objects.get(id=obj.id).STORE
        STORE_NO = Engineer.objects.get(id=obj.id).STORE_NO
        CALL_OUT_NO = Engineer.objects.get(id=obj.id).CALL_OUT_NO
        newid = obj.id
        print(newid)
        context = {
            "engineersign": engineersign,
            "CUSTOMER": CUSTOMER,
            "STORE": STORE,
            "STORE_NO": STORE_NO,
            "CALL_OUT_NO": CALL_OUT_NO,
            "newid": newid,
        }

        # html = render_to_string('pdf/rendertostring.html',context)
        # pdf = weasyprint.HTML(string=html).write_pdf()

        to_emails = ['*****@*****.**', '*****@*****.**']
        subject = "Certificate from " + CUSTOMER
        message = render_to_string('pdf/rendertostring.html', context)
        email = EmailMessage(subject,
                             body=message,
                             from_email=settings.EMAIL_HOST_USER,
                             to=to_emails)
        # email.attach("certificate.pdf", pdf, "application/pdf")
        email.content_subtype = "html"  # Main content is now text/html
        email.encoding = 'us-ascii'
        email.send()

        # renderpdf = render_to_pdf('pdf/invoice.html', data)
        # return HttpResponse(renderpdf, content_type='application/pdf')

        return redirect('rendertostring.html')
Beispiel #36
0
def haptik_users():
    users = User.objects.all()
    csvfile = StringIO.StringIO()
    csv_writer = csv.writer(csvfile,
                            delimiter=',',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['Id', 'country code', 'number', 'name'])
    for i, b in enumerate(users):
        name_fil = None
        if b.first_name:
            name = b.first_name
            name_fil = filter(lambda x: x in string.printable, name)
        csv_writer.writerow(
            [b.id, b.country_code.strip(),
             b.number.strip(), name_fil])

    message = EmailMessage('Users - Haptik', 'All current Haptik Users',
                           '*****@*****.**', EMAIL_ADDRESS)
    message.encoding = 'utf-8'
    message.attach('haptik_users.csv', csvfile.getvalue(), 'text/csv')
    message.send()
Beispiel #37
0
def task_assign_user_notify(sender, **kwargs):
    """
    Notifies assigned expert about her new task
    Receiver of signal, where sender is a Task instance
    """
    task = sender
    email = task.user.email
    subject = _('You have an assigned task')
    if Site._meta.installed:
        site = Site.objects.get_current()
        url = '%s://%s%s' % ('http', site, reverse('exmo2010:score_list_by_task', args=[task.pk]))
    else:
        url = None

    t = loader.get_template('task_user_assigned.html')
    c = Context({'task': task, 'url': url, 'subject': subject})
    message = t.render(c)

    email = EmailMessage(subject, message, config_value('EmailServer', 'DEFAULT_FROM_EMAIL'), [email])
    email.encoding = "utf-8"
    email.content_subtype = "html"
    email.send()
Beispiel #38
0
def my_send_mail(encoding='utf-8', has_attachment=False):
    """ テスト対象の関数 """

    msg = EmailMessage(
        subject='件名',
        body='本文',
        from_email='差出人 <*****@*****.**>',
        to=['送信先1 <*****@*****.**>', '送信先2 <*****@*****.**>'],
        cc=['シーシー <*****@*****.**>'],
        bcc=['ビーシーシー <*****@*****.**>'],
        reply_to=['返信先 <*****@*****.**>'],
        headers={'Sender': '*****@*****.**'})

    # エンコーディングを変更する
    msg.encoding = encoding

    if has_attachment:
        # 静的ディレクトリにあるファイルを添付する
        img = pathlib.Path(settings.STATICFILES_DIRS[0]).joinpath(
            'images', 'shinanogold.png')
        msg.attach_file(img)

    msg.send()
def encoding(request):
    """ エンコーディングの変更 """

    # デフォルトのまま送信
    EmailMessage(
        subject='件名です',
        body='My Body',
        from_email='*****@*****.**',
        to=['*****@*****.**'],
        connection=console.EmailBackend(),
    ).send()

    # ISO-2022-JPに変更して送信
    email = EmailMessage(
        subject='件名です',
        body='My Body',
        from_email='*****@*****.**',
        to=['*****@*****.**'],
        connection=console.EmailBackend(),
    )
    email.encoding = 'iso-2022-jp'
    email.send()

    return HttpResponse('encoding!')
    # to check if resources of chosen plan are over of limit.
    if o.active: 
        if o.prefered_plan.staff_size and o.care_professionals().count() > o.prefered_plan.staff_size or o.prefered_plan.student_size and o.get_student_().count() > o.prefered_plan.student_size:
            s += u"--- %s - %s/admin/organization/organization/%s/\n" % (o.name, URL_APP, o.id)

            if o.prefered_plan.staff_size and o.care_professionals().count() > o.prefered_plan.staff_size:
                s += u"Professional %s Plan %s\n" % (o.care_professionals().count(), o.prefered_plan.staff_size)

            if o.prefered_plan.student_size and  o.get_student_().count() > o.prefered_plan.student_size:
                s += u"Student %s Plan %s\n" % (o.get_student_().count(), o.prefered_plan.student_size)

            s += u'\n'

# send email if not empty list for both
if s and ADMINS_REGISTRATION:
    # sendmail
    msg = EmailMessage()
    msg.encoding = "utf-8"
    msg.subject = u"GestorPsi - orgs over of limit - %s " % datetime.today()
    msg.body = s
    msg.to = ADMINS_REGISTRATION
    msg.send()

'''
    Check all invoices. If is a overdue invoice, payment way will be billet.
'''
expiry = date.today()-timedelta(1) # yesterday
for x in Invoice.objects.filter(expiry_date=expiry, status=0).exclude(payment_type=2): # overdue, is not billet.
    x.payment_type = PaymentType.objects.get(pk=2) # billet, hardcode
    x.save()
Beispiel #41
0
def send_email():
    now = datetime.now()
    now_str = now.strftime("%Y-%m-%d")
    date_str = now.strftime("%Y%m%d")
    zone_list = AmazonRefShopList.objects.filter(
        type="feedback").values("zone").distinct().all()
    # print(zone_list)
    zones = [zone['zone'] for zone in zone_list]
    zone_feedback_list = []
    for zone in zones:
        shop_list = AmazonRefShopList.objects.filter(zone=zone).filter(
            type="feedback").order_by("shop_name")
        # print(shop_list)
        ordering = 'CASE WHEN shop_name="NEON MART" THEN 1 ELSE 2 END'
        feedback_count_list = FeedbackInfo.objects.filter(date=now_str).filter(
            zone=zone).extra(select={'ordering': ordering},
                             order_by=('ordering', 'shop_name'))
        shop_url_dict = dict(
            (shop.shop_name, shop.shop_url) for shop in shop_list)
        feedback_table_data = []
        for feedback_count in feedback_count_list:
            feedback_table_data.append({
                'date':
                feedback_count.date.strftime("%Y-%m-%d"),
                'shop_name':
                feedback_count.shop_name,
                'shop_url':
                shop_url_dict[feedback_count.shop_name],
                'last_30_days':
                feedback_count.last_30_days,
                'last_90_days':
                feedback_count.last_90_days,
                'last_12_months':
                feedback_count.last_12_months,
                'lifetime':
                feedback_count.lifetime,
                'last_day':
                feedback_count.last_day,
                'last_week':
                feedback_count.last_week,
                'last_month':
                feedback_count.last_month,
                'zone':
                feedback_count.zone,
            })
        zone_feedback_list.append(feedback_table_data)

    email_template_name = '../templates/monitor/email.html'
    t = loader.get_template(email_template_name)
    context = {'zone_feedback_list': zone_feedback_list, 'date': now_str}
    html_content = t.render(context)
    #send_mail('Feedback统计'+date_str,
    #          '',
    #          settings.EMAIL_FROM,
    #          settings.EMAIL_TO,
    #          html_message=html_content)

    msg = EmailMessage('Feedback统计' + date_str, html_content,
                       settings.EMAIL_FROM, settings.EMAIL_TO)
    msg.content_subtype = 'html'
    msg.encoding = 'utf-8'
    image_path = feedback_image()
    image = add_img(image_path, 'test_cid')
    msg.attach(image)
    if msg.send():
        return True
    else:
        return False
Beispiel #42
0
    def form_valid(self, form, detalle_compra_form_set):

        #obtenemos la ultima de su  serie prara generar un nuevo numero
        qsComp_last = Compra.objects.filter(
            lfact=form.instance.titular.letra).order_by('nfact').last()

        if qsComp_last:
            form.instance.nfact = qsComp_last.nfact + 1
        else:
            form.instance.nfact = 1
        form.instance.lfact = form.instance.titular.letra

        self.object = form.save()
        detalle_compra_form_set.instance = self.object
        detalle_compra_form_set.save()
        total_base = 0

        detalles = DetalleCompra.objects.filter(
            compra=self.object).order_by('pk')
        for detalle in detalles:
            d = {
                'producto': detalle.producto,
                'cantidad': detalle.cantidad,
                'precio_compra': detalle.precio_compra
            }

            #sumamos los kilos de cada detalle en su almacen(silo)
            #p = Producto.objects.get(descripcion=detalle.producto)
            #p.kilos = p.kilos + detalle.cantidad
            #p.save()

            detalle.producto.kilos += detalle.cantidad
            detalle.producto.save()

            # si el producto entra a un silo con lote
            if detalle.producto.lote:
                detalle.lote_heredado = detalle.producto.lote
                print("detalle lote", detalle.lote_heredado)
                detalle.save()
                #detalle.save(update_fields=["lote_heredado"])
                #DetalleVenta.objects.get(pk=detalle.pk).save(update_fields=["lote_heredado"])

            #qs = DetalleVenta.objects.get(pk =detalle.pk)
            #print("guardado en historico ", qs.producto, qs.cantidad, qs.precio_venta, qs.lote_heredado)
            Historico.objects.create(compra=detalle.compra,
                                     producto=detalle.producto,
                                     cantidad=detalle.cantidad,
                                     precio_compra=detalle.precio_compra,
                                     fecha=detalle.fecha,
                                     lote_heredado=detalle.lote_heredado,
                                     kilos_actuales=detalle.producto.kilos)

            #calculamos su precio base
            total_detalle = detalle.cantidad * detalle.precio_compra
            print("valores en €")
            print(detalle.producto, total_detalle)
            total_base = total_base + total_detalle

        print("base ", total_base)
        #aplicamos impuestos
        form.instance.base = total_base
        form.instance.imp_aplicado = total_base * form.instance.impuestos.impuesto1 / 100
        print("valor de impuestto 1 ", form.instance.imp_aplicado)
        #Comprobamos si hay un segundo impuesto a aplicar
        if form.instance.impuestos.impuesto2:
            if form.instance.impuestos.se_calcula_con == "BASE":
                form.instance.imp_aplicado = form.instance.imp_aplicado + total_base * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 BASE ",
                      form.instance.imp_aplicado)
            if form.instance.impuestos.se_calcula_con == "TOTAL":
                form.instance.imp_aplicado = form.instance.imp_aplicado + (
                    form.instance.imp_aplicado +
                    total_base) * form.instance.impuestos.impuesto2 / 100
                print("calculando impuesto 2 TOTAL",
                      form.instance.imp_aplicado)
        form.instance.total = total_base + form.instance.imp_aplicado

        print("impuestos ", form.instance.imp_aplicado)
        print("total", form.instance.total)

        form.instance.save()

        ############# PDF ###################

        # obtenemos los detalles de esta facuta para crear un nested dict
        detalles = DetalleCompra.objects.filter(compra=form.instance.pk)
        lineas = {}
        i = 1
        for d in detalles:
            detalle_total = d.precio_compra * d.cantidad
            lineas['linea' + str(i)] = {
                'producto': d.producto.variedad,
                'cantidad': d.cantidad,
                'precio': d.precio_compra,
                'total': detalle_total,
                'lote_heredado': d.lote_heredado
            }
            i = i + 1

        compra = Compra.objects.get(pk=form.instance.pk)
        context = {
            'numero': compra.nfact,
            'fecha': compra.fecha,
            'forma_pago': compra.forma_pago,
            'titular_nombre': compra.titular.nombre,
            'titular_cif': compra.titular.cif,
            'titular_direccion': compra.titular.direccion,
            'proveedor_nombre': compra.proveedor.razon_social,
            'proveedor_ruc': compra.proveedor.ruc,
            'proveedor_direccion': compra.proveedor.direccion,
            'proveedor_certificado': compra.proveedor.entidad_certificadora,
            'base': compra.base,
            'impuestos': compra.impuestos,
            'imp_aplicado': compra.imp_aplicado,
            'total': compra.total,
            'lineas': lineas
        }
        print(context)
        '''context = {
            'acta': qsacta,
            'laboratorio': qslaboratorio,
            'muestreo': qsmuestreo,
            'pk': pk,
            'tipo': tipo
        }'''

        template_path = 'plantilla_email.html'
        template = get_template(template_path)
        # html = template.render(form.instance.__dict__)
        html = template.render(context)
        # print(form.instance.__dict__)

        ## definir los datos del diccionario, este no sirve
        ## hacer bien los estilos, los de boostrap no funcionan
        ## los estilos que soporta estan bastante limitados
        ## https://xhtml2pdf.readthedocs.io/en/latest/reference.html#supported-css-properties

        ndocumento1 = "factura" + str(form.instance.nfact) + ".pdf"
        #ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento1)
        ddocumento = ndocumento1
        outFilename = ddocumento
        outFile = open(outFilename.encode("utf-8"), "w+b")
        pisaStatus = pisa.CreatePDF(html.encode('utf-8'),
                                    dest=outFile,
                                    encoding='utf-8')
        outFile.close()
        ndocumento = ddocumento
        # ddocumento = os.path.join(settings.MEDIA_ROOT, ndocumento)
        leerdocumento = open(ddocumento.encode("utf-8"), "rb").read()

        ############### EMAIL ##################33

        b = base64.b64encode(leerdocumento).decode("utf-8", "ignore")

        nombredocumento = "factura" + str(form.instance.nfact) + ".pdf"
        email = "*****@*****.**"
        asunto = "Factura de compra"
        cuerpo = "Buenos dias, adjuntamos factura de compra"
        body = cuerpo
        # Replace this texto in plantilla cuerpo
        body_content = mark_safe(body)
        html_content = mark_safe(body_content)
        remitente = settings.EMAIL_HOST_USER
        destinatario = email
        try:
            msg = EmailMessage(asunto, html_content, remitente, [destinatario])
            msg.attach(nombredocumento, leerdocumento, "application/pdf")
            msg.content_subtype = "pdf"  # Main content is now text/html
            msg.encoding = 'utf-8'
            msg.send()
            print("mensaje enviado ")
        except Exception as e:
            print("no se ha podido enviar ", e)

        return HttpResponseRedirect(self.success_url)
Beispiel #43
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()