Beispiel #1
0
 def send_mail(self):
     # need to ensure address is minimally valid email
     sent_emails = ['', None]
     with open(os.path.join(
         BASE_DIR,
         'registration/static/registration/email_text/genericbanner.png'
     ), 'rb') as fp:
         image1 = MIMEImage(fp.read())
     image1.add_header('Content-ID', '<{}>'.format('image1'))
     for key in self._recipients:
         reg_id = key
         address = self._recipients[key]['email']
         salutation = self._recipients[key]['salutation']
         email_body = self._message
         if address not in sent_emails:
             if salutation not in ('', None):
                 email_body = 'Dear ' + salutation + ':<br/><br/>' + \
                     self._message
             if self._msg_type in ('docs', 'thanks'):
                 email_body = self._insert_passwords(email_body, key)
             email_body = '<img src="cid:image1" style="width:auto; max-width:90%;"/><br/><br/>' + email_body
             email_body = '<html><body>' + email_body + '</body></html>'
             email = EmailMessage(
                 subject = self._subject,
                 body = email_body,
                 to = [address]
             )
             email.content_subtype = 'html'
             email.mixed_subtype = 'related'
             email.attach(image1)
             email.send()
             sent_emails.append(address)
             time.sleep(SLEEP_TIME)
Beispiel #2
0
 def send_mail(self):
     # need to ensure address is minimally valid email
     sent_emails = ['', None]
     with open(
             os.path.join(
                 BASE_DIR,
                 'registration/static/registration/email_text/genericbanner.png'
             ), 'rb') as fp:
         image1 = MIMEImage(fp.read())
     image1.add_header('Content-ID', '<{}>'.format('image1'))
     for key in self._recipients:
         reg_id = key
         address = self._recipients[key]['email']
         salutation = self._recipients[key]['salutation']
         email_body = self._message
         if address not in sent_emails:
             if salutation not in ('', None):
                 email_body = 'Dear ' + salutation + ':<br/><br/>' + \
                     self._message
             if self._msg_type in ('docs', 'thanks'):
                 email_body = self._insert_passwords(email_body, key)
             email_body = '<img src="cid:image1" style="width:auto; max-width:90%;"/><br/><br/>' + email_body
             email_body = '<html><body>' + email_body + '</body></html>'
             email = EmailMessage(subject=self._subject,
                                  body=email_body,
                                  to=[address])
             email.content_subtype = 'html'
             email.mixed_subtype = 'related'
             email.attach(image1)
             email.send()
             sent_emails.append(address)
             time.sleep(SLEEP_TIME)
Beispiel #3
0
    def __generate_messages(self, subject, body, template, to_emails, request):
        """
        Generate email message from Django template
        :param subject: Email message subject
        :param template: Email template
        :param to_emails: to email address[es]
        :return:
        """
        messages = []

        if template:
            message_template = get_template(template)
            for recipient, context in to_emails.items():
                message_content = message_template.render(context)
                html_mail = weasyprint.HTML(
                    string=message_content,
                    base_url=request.build_absolute_uri())
                pdf = html_mail.write_pdf(presentational_hints=True)
                message = EmailMessage(subject,
                                       body,
                                       to=[recipient],
                                       from_email=self.from_email)
                message.content_subtype = 'html'
                message.attach('payslip.pdf', pdf, 'application/pdf')
                message.mixed_subtype = 'related'
                messages.append(message)
        else:
            for recipient in to_emails:
                message = EmailMessage(subject,
                                       body,
                                       to=[recipient],
                                       from_email=self.from_email)
                messages.append(message)

        return messages
Beispiel #4
0
    def sending_email(self, type_id, email=None, new_offer=None):
        global subject, message
        if not email:
            email = EMAIL_ADMIN
        target_emails = [email]

        vars = dict()
        if type_id == 1:
            subject = "Новая заявка на публикацию заказа"
            vars["new_offer"] = new_offer
            subject = 'Клиент подал заявку на публикацию заказа'
            message = get_template(
                'emails_templates/notification_admin.html').render(vars)

        elif type_id == 2:
            subject = 'Ваша заявка получена! Модератор уже её проверяет!'
            vars["new_offer"] = new_offer
            message = get_template(
                'emails_templates/notification_customer.html').render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=self.from_email,
                           to=target_emails,
                           bcc=self.bcc_emails,
                           reply_to=self.reply_to_emails)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        kwargs = {"type_id": type_id, "email": email}
        if new_offer:
            kwargs["offer"] = new_offer
        EmailSendingFact.objects.create(**kwargs)
def send_attendance_start_email(attendance):
    # print(attendance)

    subject = 'Atendimento solicitado - Checa Aqui'
    # message = f'Ativação de email, Token de ativação: {token}'
    html_message = render_to_string(
        'attendance_start_email.html', {
            'attendant': attendance.attendant,
            'client': attendance.client,
            'product': attendance.product,
            'phone': attendance.client.profile.phone
        })

    image_path = os.path.join(BASE_DIR, os.path.join('templates',
                                                     'Ativo 1.png'))
    print(image_path)

    email = EmailMessage(subject, html_message, EMAIL_HOST_USER,
                         [attendance.attendant.profile.email])

    email.content_subtype = "html"
    email.mixed_subtype = 'related'

    with open(image_path, mode='rb') as file:
        image = MIMEImage(file.read())
        email.attach(image)
        image.add_header('Content-ID', f"<Ativo_1>")

    email.send()
Beispiel #6
0
def home(request):
    Data = {}

    if request.method == 'POST':
        hoten = request.POST.get('name')
        email = request.POST.get('email')
        sdt = request.POST.get('sdt')
        tinnhan = request.POST.get('message')

        lienhe_obj = LienHe(HoTen=hoten, Email=email, SDT=sdt, TinNhan=tinnhan)
        lienhe_obj.save()

        mail_subject_admin = 'Bạn có một tin nhắn mới.'
        message_admin = render_to_string('simso/chitiettinnhan.html', {
            'HoTen': hoten,
            'Email': email,
            'SDT': sdt,
            'TinNhan': tinnhan,
        })
        to_email_admins = CustomerUser.objects.get(is_superuser=True).email
        email_admin = EmailMessage(mail_subject_admin,
                                   message_admin,
                                   to=[to_email_admins])
        email_admin.content_subtype = 'html'
        email_admin.mixed_subtype = 'related'
        email_admin.send()

        return render(request, 'simso/guitinnhanthanhcong.html', Data)

    return render(request, 'simso/contact.html', Data)
Beispiel #7
0
    def sending_email(self, type_id, email=None, order=None):
        global subject, message
        if not email:
            email = EMAIL_ADMIN
        target_emails = [email]

        vars = dict()
        if type_id == 1:
            subject = "Новая заявка"
            vars["order"] = order
            subject = 'Клиент подал заявку. Ответьте на вопрос!'
            message = get_template(
                'emails_templates/notification_admin.html').render(vars)

        elif type_id == 2:
            subject = 'Ваша заявка получена! Ожидайте ответа, скоро с Вами свяжется наш оператор!'
            vars["order"] = order
            message = get_template(
                'emails_templates/notification_customer.html').render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=self.from_email,
                           to=target_emails,
                           bcc=self.bcc_emails,
                           reply_to=self.reply_to_emails)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        kwargs = {"type_id": type_id, "email": email}
        if order:
            kwargs["customer"] = order
        EmailSendingFact.objects.create(**kwargs)
Beispiel #8
0
def add_list(request):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        new_feedback = form.save()
        subject = request.POST.get('Проблема')
        from_email = request.POST.get('email')
        receiver = ['*****@*****.**', '*****@*****.**']

        feedback_item_data = model_to_dict(new_feedback)
        print(feedback_item_data)
        vars = {
            'data': feedback_item_data,
        }

        message = get_template('primer/add_list.html').render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=from_email,
                           to=receiver)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        #send_mail(subject, message, from_email,['[email protected],','*****@*****.**'], fail_silently=False)
        #return HttpResponse('/thanks/')
        return HttpResponseRedirect('/thanks/')

        #send_mail('ГБУ "Жилижник района Южное Медведково', request.POST.get('text'),  '*****@*****.**',['*****@*****.**','*****@*****.**'], fail_silently=False)
        #send_mail('ГБУ "Жилижник района Южное Медведково', ' Сообщение о проблемной теме: datasent: %s %s %s'%(name,text,email), '*****@*****.**',   ['*****@*****.**','*****@*****.**'], fail_silently=False)
        return HttpResponseRedirect('/index2/')
    return render(request, 'primer/add_list.html', {'form': form})
Beispiel #9
0
    def sending_email(self, type_id):
        if type_id == 1:
            subject = "Новая новость"
            message = render_to_string('emails_template/new.html')

        msg = EmailMessage(subject, message, reply_to=self.replay_to_email)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()
Beispiel #10
0
    def post(self, request, *args, **kwargs):
        alert = ''
        form = RegistrationForm(request.POST)

        if form.is_valid():
            event_receiver_email = form.cleaned_data['email']
            form.save()

            allowed = False

            try:
                allowed = (EmailContent.objects.get(
                    event=self.event)).mail_allowed
            except EmailContent.DoesNotExist:
                pass

            if allowed:
                content = EmailContent.objects.get(event=self.event)
                all_files = EmailAttachment.objects.filter(event=self.event)

                subject = content.subject
                message = render_to_string('event_email_template.html', {
                    'content': content,
                    'event': self.event,
                })

                from_mail = EMAIL_HOST_USER
                to_mail = [event_receiver_email]

                mail = EmailMessage(subject, message, from_mail, to_mail)
                mail.content_subtype = "html"
                mail.mixed_subtype = 'related'

                image_sub_type = (str(self.event.pic_path).split('.'))[-1]
                event_image = MIMEImage(self.event.pic_path.read(),
                                        _subtype=image_sub_type)
                event_image.add_header('Content-ID',
                                       '<{}>'.format(self.event.pic_path))
                mail.attach(event_image)

                for single_file in all_files:
                    mail.attach(filename=single_file.name,
                                content=single_file.files.read())

                mail.send()
            messages.add_message(request, messages.SUCCESS,
                                 "Successfully registered.")
            return redirect(reverse_lazy('registration'))
        else:
            if '__all__' in dict(form.errors):
                alert = dict(form.errors)['__all__']
            return render(request, 'registration.html', {
                'form': form,
                'event': self.event,
                'alert': alert
            })
Beispiel #11
0
def notify_users_about_challenge(request):
    """
    Email New Challenge Details to EvalAI Users
    """
    if request.user.is_authenticated() and request.user.is_superuser:
        if request.method == 'GET':
            template_name = 'notification_email_data.html'
            return render(request, template_name)

        elif request.method == 'POST':
            users = User.objects.exclude(email__exact='').values_list(
                'email', flat=True)
            subject = request.POST.get('subject')
            body_html = request.POST.get('body')

            try:
                challenge_image = request.FILES['challenge_image']
            except:
                challenge_image = None

            if challenge_image:
                image = MIMEImage(challenge_image.read())
                image.add_header('Content-Disposition',
                                 'inline',
                                 filename=challenge_image._name)
                image.add_header('Content-ID', '{}'.format(challenge_image))

            sender = settings.CLOUDCV_TEAM_EMAIL

            email = EmailMessage(subject,
                                 body_html,
                                 sender, [settings.CLOUDCV_TEAM_EMAIL],
                                 bcc=users)
            email.content_subtype = 'html'

            if challenge_image:
                email.mixed_subtype = 'related'
                email.attach(image)

            try:
                email.send()
                return render(
                    request, 'notification_email_conformation.html',
                    {'message': 'All the emails are sent successfully!'})
            except SMTPException:
                logger.exception(traceback.format_exc())
                return render(request, 'notification_email_data.html',
                              {'errors': 1})
        else:
            return render(request, 'error404.html')
    else:
        return render(request, 'error404.html')
Beispiel #12
0
def add_list(request):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        new_feedback = form.save()

        subject = request.POST.get('',
                                   'ГБУ "ЖИЛИЩНИК РАЙОНА ЮЖНОЕ МЕДВЕДКОВО"')
        from_email = request.POST.get('email')

        receiver = ['*****@*****.**']
        """
        Your old code for emails sending is below
        """
        #msg = EmailMessage(subject, message, from_email, [receiver])
        #msg.content_subtype = 'primer/add_list.html'
        #msg.send()
        """
        CodingMedved code for emails sending
        """
        feedback_item_data = model_to_dict(new_feedback)
        print(feedback_item_data)
        vars = {
            'data': feedback_item_data,
        }

        message = get_template('primer/add_list.html').render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=from_email,
                           to=receiver)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        #send_mail(subject, message, from_email,['[email protected],','*****@*****.**'], fail_silently=False)
        return HttpResponse(
            'Спасибо уважаемый пользователь! Ваше сообщение отправлено!')

        #send_mail('ГБУ "Жилижник района Южное Медведково', request.POST.get('text'),  '*****@*****.**',['*****@*****.**','*****@*****.**'], fail_silently=False)
        #send_mail('ГБУ "Жилижник района Южное Медведково', ' Сообщение о проблемной теме: datasent: %s %s %s'%(name,text,email), '*****@*****.**',   ['*****@*****.**','*****@*****.**'], fail_silently=False)
        return HttpResponseRedirect('/index2/')
    return render(request, 'primer/add_list.html', {'form': form})


# def add_list (request):
#     form = FeedbackForm(request.POST or None)
#     if request.POST:
#         person = Feedback(name=request.POST.get('person_name'))
#         person.save()
#         return HttpResponseRedirect('/index2/')
#     return render(request, 'primer/add_list.html')
Beispiel #13
0
 def send_mail(self, email):
     html = get_template('mytest/email.html')
     d = Context({'input_data': self.input_data,
                 'result': self.result,
                 'email': email})
     html_content = html.render(d)
     msg = EmailMessage(u'Результат высисления',
                        html_content,
                        '*****@*****.**',
                        [email, '*****@*****.**'])
     msg.content_subtype = "html"
     msg.mixed_subtype = 'related'
     msg.send()
Beispiel #14
0
def mualuon(request, DuongDan):
    if request.method == 'POST':
        daugia = DauGia.objects.filter(DuongDan=request.POST.get('DuongDan'))[0]
        daugia.GiaHienTai = daugia.GiaMuaLuon
        daugia.NguoiDauGiaHienTai = request.user
        daugia.DaDauGia = True
        daugia.save()

        #Gửi thông tin hóa đơn cho người dùng và admin
        user = request.user
        import pdb; pdb.set_trace()
        mail_subject = '[Sim Đức Lộc] Thông tin đấu giá.'
        message = render_to_string('simso/page-daugia/thongtindaugia.html', {
            'user': user,
            'DauGia': daugia,
        })
        to_email = user.email
        email = EmailMessage(
            mail_subject, message, to=[to_email]
        )
        email.content_subtype = 'html'
        email.mixed_subtype = 'related'
        email.send()


        mail_subject_admin = 'Đấu giá kết thúc.'
        message_admin = render_to_string('simso/page-daugia/thongtindaugiaadmin.html', {
            'User': user,
            'DauGia': daugia,
        })
        to_email_admins = CustomerUser.objects.get(is_superuser=True).email
        email_admin = EmailMessage(
            mail_subject_admin, message_admin, to=[to_email_admins]
        )
        email_admin.content_subtype = 'html'
        email_admin.mixed_subtype = 'related'
        email_admin.send()

        return redirect('DauGia:chitietdaugia', daugia.DuongDan)
Beispiel #15
0
    def post(self, request, *args, **kwargs):
        alert = ''
        form = RegistrationForm(request.POST)

        if form.is_valid():
            event_receiver_email = form.cleaned_data['email']
            form.save()

            allowed = False

            try:
                allowed = (EmailContent.objects.get(event=self.event)).mail_allowed
            except EmailContent.DoesNotExist:
                pass

            if allowed:
                content = EmailContent.objects.get(event=self.event)
                all_files = EmailAttachment.objects.filter(event=self.event)

                subject = content.subject
                message = render_to_string('event_email_template.html', {
                    'content': content,
                    'event': self.event,
                })

                from_mail = EMAIL_HOST_USER
                to_mail = [event_receiver_email]

                mail = EmailMessage(subject, message, from_mail, to_mail)
                mail.content_subtype = "html"
                mail.mixed_subtype = 'related'

                image_sub_type = (str(self.event.pic_path).split('.'))[-1]
                event_image = MIMEImage(self.event.pic_path.read(), _subtype=image_sub_type)
                event_image.add_header('Content-ID', '<{}>'.format(self.event.pic_path))
                mail.attach(event_image)

                for single_file in all_files:
                    mail.attach(filename=single_file.name,
                                content=single_file.files.read())

                mail.send()
            messages.add_message(request, messages.SUCCESS,
                                 "Successfully registered.")
            return redirect(reverse_lazy('registration'))
        else:
            if '__all__' in dict(form.errors):
                alert = dict(form.errors)['__all__']
            return render(request, 'registration.html', {'form': form, 'event': self.event, 'alert':alert})
Beispiel #16
0
def sending_email(site, user, current_site, code, to_email):
    mail_subject = 'Thanks for choosing our App'
    message = render_to_string(
        site, {
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': account_activation_token.make_token(user),
            'code': code,
        })
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.content_subtype = 'html'
    email.mixed_subtype = 'related'

    email.send()
Beispiel #17
0
    def sending_email(self, type_id, email=None, order=None):
        if not email:
            email = EMAIL_ADMIN
        target_emails = [email]

        vars = {}

        if type_id == 1:  # admin
            subject = "Новый заказ ТВ-МАСТЕРСКАЯ"
            vars["order_fields"] = model_to_dict(order)
            vars["order"] = order
            vars["products_in_order"] = order.productinorder_set.filter(
                is_active=True)
            message = get_template(
                'emails/order_notification_admin.html').render(vars)

        elif type_id == 2:  #customer not
            subject = "Ваш заказ получен 'СЦ на Богатырском 36'"
            vars["order_fields"] = model_to_dict(order)
            vars["order"] = order
            vars["products_in_order"] = order.productinorder_set.filter(
                is_active=True)
            message = get_template(
                'emails/order_notification_customer.html').render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=self.from_email,
                           to=target_emails,
                           bcc=self.bcc_emails,
                           reply_to=self.reply_to_emails)
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        kwargs = {
            "type_id": type_id,
            "email": email,
        }
        if order:
            kwargs["order"] = order

        EmailSendingFact.objects.create(**kwargs)
        print("Email send!")
Beispiel #18
0
def send_email(mail):
    if mail.flight_tichet:
        att_mail = EmailMessage(
            mail.title or 'ebiassy',
            mail.message,
            settings.EMAIL_HOST_USER,
            [mail.email],
        )
        att_mail.attach(mail.flight_tichet.name, mail.flight_tichet.read(),
                        mail.flight_tichet_content_type)
        att_mail.content_subtype = 'html'
        att_mail.mixed_subtype = 'related'
        att_mail.send()
    else:
        # there is not attachement
        send_mail(mail.title or 'ebiassy',
                  mail.message,
                  settings.EMAIL_HOST_USER, (mail.email, ),
                  fail_silently=False,
                  html_message=mail.message)
def send_validation(email, token):
    subject = 'Validação de email - Checa Aqui'
    # message = f'Ativação de email, Token de ativação: {token}'
    html_message = render_to_string('validation_email.html', {'token': token})
    image_path = os.path.join(BASE_DIR, os.path.join('templates',
                                                     'Ativo 1.png'))
    print(image_path)

    email = EmailMessage(subject, html_message, EMAIL_HOST_USER, [email])
    email.content_subtype = "html"
    email.mixed_subtype = 'related'

    with open(image_path, mode='rb') as file:
        image = MIMEImage(file.read())
        email.attach(image)
        image.add_header('Content-ID', f"<Ativo_1>")

    email.send()

    return False
Beispiel #20
0
def spam():
    subject, from_email, to = 'Shaastra 2013 invitation', '*****@*****.**', '*****@*****.**'
    #text_content = 'Please find attached the Shaastra 2011 invitation'
    html_content = '<img src = "http://www.shaastra.org/2011/media/main/img/all_logos.png>"'
    #msg = EmailMultiAlternatives(subject, text_content, from_email, [to])# sending plain text in case they cant view html
    #msg.attach_alternative(html_content, "text/html")# the additional html content added to the content for ppl who can view html content
    #send_html_mail(subject,html_content,from_email,[to])
    img_data = open('/var/www/invite.jpg', 'rb').read()
    img_content_id = 'noname'
    body = '<img src="cid:%s" />' % img_content_id
    msg = EmailMessage('tite4', body, '*****@*****.**', ['*****@*****.**'], headers = {'Content-ID': img_content_id,'Content-Disposition' : 'inline'})
    msg.mixed_subtype = 'relative'

    #msg.mixed_subtype = 'multipart/related'
    img = MIMEImage(img_data)
    img.add_header('Content-ID', '<%s>' % img_content_id)
    img.add_header('Content-Disposition', 'inline')

    msg.attach(img)
    msg.send()
Beispiel #21
0
    def sending_emails(self, type_id, email=None):
        global subject, message
        if not email:
            email = EMAIL_ADMIN
        target_emails = [email]

        vars = {

        }  # vars()

        if type_id == 1:  # to Admin
            subject = "Новый заказ."
            #vars["order_fields"] = model_to_dict(order)  # model to dict
            #vars["order"] = order
            #vars["products_in_order"] = order.productinorder_set.filter(is_activee=True)
            message = get_template('emails_templates/order_notification_admin.html').render(vars)

        if type_id == 2:  # to Customer
            subject = 'Ваш заказ принят нашим магазином!'
            message = get_template('emails_templates/order_notification_customer.html').render(vars)

        msg = EmailMessage(
            subject, message, from_email=self.from_email,
            to=target_emails, bcc=self.bcc_emails, reply_to=self.reply_to_emails
        )

        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()

        kwargs = {
            "type_id": type_id,
            "email": email
        }

        # if order:
        #     kwargs["order"] = order
        EmailSendingFact.objects.create(**kwargs)

        print('Email was sent successfully!')
    def sending_email(self, type_id, email=None, order=None):

        if not email:
            email = EMAIL_ADMIN
        target_emails = [email]

        vars = dict()

        if type_id == 1:  # admin notification
            subject = "Новый заказ"
            vars["order_fields"] = model_to_dict(order)
            vars["order"] = order
            vars["products_in_order"] = order.productinorder_set.filter(
                is_active=True)
            message = get_template(
                "shop/order_notification_admin.html").render(vars)

        elif type_id == 2:  # customer notification
            subject = "Ваш заказ принят в обработку. Наш менеджер свяжется с вами в ближайшее время! Спасибо, что вы с нами!"
            message = get_template(
                "shop/order_notification_customer.html").render(vars)

        msg = EmailMessage(subject,
                           message,
                           from_email=self.from_email,
                           to=target_emails,
                           bcc=self.bcc_emails,
                           reply_to=self.reply_to_emails)
        msg.content_subtype = "html"
        msg.mixed_subtype = "related"
        msg.send()

        kwargs = {"type_id": type_id, "email": email}

        if order:
            kwargs["order"] = order
        EmailSendingFact.objects.create(**kwargs)

        print("Email was sent successfully!")
Beispiel #23
0
 def post(self, request):
     if request.method == 'POST':
         user_form = CreateUserForm(request.POST)
         register_form = RegisterForm(request.POST, request.FILES)
         if user_form.is_valid():
             user = user_form.save(commit=False)
             user.is_active = False
             user.save()
             user_form_id = user_form.instance.id
             register_form.instance.user_id = user_form_id
             if register_form.is_valid():
                 register_form.save()
                 current_site = get_current_site(request)
                 mail_subject = 'Activate your account.'
                 username = user_form.cleaned_data.get('username')
                 message = render_to_string('active_email.html', {
                     'user': user,
                     'domain': current_site.domain,
                     'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                     'token': default_token_generator.make_token(user),
                 })
                 to_email = user_form.cleaned_data.get('email')
                 image_data = open('static/img/LOGO150x40.png', 'rb').read()
                 image = MIMEImage(image_data, 'png')
                 image.add_header('Content-ID', '<embed_image>')
                 email = EmailMessage(mail_subject, message, to=[to_email])
                 email.attach(image)
                 email.content_subtype = "html"
                 email.mixed_subtype = 'related'
                 email.send()
                 return redirect('register-confirm')
         else:
             print(f"Error like: {user_form.errors}")
             print(f"Error like: {register_form.errors}")
     else:
         context = {'user_form': user_form, 'register_form': register_form}
         return render(request, self.template_name, context)
Beispiel #24
0
def thanhcong(request):
    user = request.user
    cart_obj, cart_created = GioHang.objects.new_or_get(request)
    ctgh = CTGH.objects.filter(GH=cart_obj)
    order_obj = None

    if cart_created:
        return redirect("giohang:home")
    else:
        order_obj, new_order_obj = HoaDon.objects.get_or_create(GH=cart_obj)

    #Gửi thông tin hóa đơn cho người dùng và admin
    mail_subject = '[Sim Đức Lộc] Thông tin hóa đơn.'
    message = render_to_string(
        'simso/page-cart/thongtinhoadon.html', {
            'user': user,
            'Ctghs': ctgh,
            'Cart_obj': cart_obj,
            'Order_obj': order_obj,
        })
    to_email = user.email
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.content_subtype = 'html'
    email.mixed_subtype = 'related'
    email.send()

    mail_subject_admin = 'Bạn có một đơn đặt hàng mới.'
    message_admin = render_to_string(
        'simso/page-cart/thongtinhoadonadmin.html', {
            'User': user,
            'Ctghs': ctgh,
            'Cart_obj': cart_obj,
            'Order_obj': order_obj,
        })
    to_email_admins = CustomerUser.objects.get(is_superuser=True).email
    email_admin = EmailMessage(mail_subject_admin,
                               message_admin,
                               to=[to_email_admins])
    email_admin.content_subtype = 'html'
    email_admin.mixed_subtype = 'related'
    email_admin.send()

    request.session['cart_items'] = 0

    # Thay đổi trạng thái thanh toán của hóa đơn khi thanh toán bằng paypal
    if request.GET.get('st') and request.GET.get('st') == 'Completed':
        order_obj.ThanhToan = True
        order_obj.save()
    del request.session['cart_id']

    stl = SimTheoLoai.objects.all()
    sns = SimNamSinh.objects.all()
    nm = NhaMang.objects.all()
    stg = SimTheoGia.objects.all()
    # Sắp xếp danh mục sim theo giá theo title
    stg_dsx = sorted(stg, key=operator.attrgetter('title'))
    Data = {
        "stl": stl,
        "sns": sns,
        "nm": nm,
        "stg": stg_dsx,
    }
    return render(request, 'simso/page-cart/thanhcong.html', Data)