コード例 #1
0
ファイル: views.py プロジェクト: shacker/ccademo
def follow(request,username):
    """
    Let one user follow another.
    """

    follower = get_object_or_404(Profile,user=request.user)
    followee = get_object_or_404(Profile,user__username=username)

    # Is current user already following this list/profile?
    if followee in follower.followees.all():
        messages.info(request, "You were already following %s" % followee)
    else:
        follower.followees.add(followee)

        # Only send email if followee has that option enabled in their profile
        if followee.email_on_follow == True:

            site = Site.objects.get(id=1) # Need this for link in email template.
            recipients = [followee.user.email,]
            email_subject = render_to_string("people/follow/followed-subject.txt", { 'follower': follower, 'followee': followee })
            email_body_txt = render_to_string("people/follow/followed-body.txt", { 'follower': follower, 'followee': followee, 'site': site, })

            msg = EmailMessage(email_subject, email_body_txt, settings.DEFAULT_FROM_EMAIL, recipients)
            msg.send(fail_silently=False)

        messages.success(request, "You are now following %s" % followee)

    return HttpResponseRedirect(reverse('people_profile_detail',args=[username]))
コード例 #2
0
ファイル: models.py プロジェクト: 7mp/django-form-designer
    def send_mail(self, form, files=[]):
        # TODO: refactor, move to utils
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_context(form_data)

        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
コード例 #3
0
ファイル: tests.py プロジェクト: 6ft/django
 def test_ascii(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'], 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '*****@*****.**')
コード例 #4
0
ファイル: views.py プロジェクト: danielgtaylor/arista-website
def preset_submit(request):
    if request.method == "POST":
        form = SubmitForm(request.POST, request.FILES)
        
        if form.is_valid():
            preset = request.FILES["preset_file"]
            message = EmailMessage(**{
                "subject": "[Arista] Preset for %s" % preset.name[:-8],
                "body": "A user has uploaded a new preset!",
                "from_email": form.cleaned_data["email"],
                "to": [x[1] for x in settings.ADMINS],
                "attachments": [
                    (preset.name, preset.read(), "application/x-bzip-compressed-tar"),
                ],
            })
            
            message.send()
        
            return HttpResponseRedirect("/presets/?thanks=1")
    else:
        form = SubmitForm()
    
    return render(request, "presets/submit.html", {
        "form": form,
    })
コード例 #5
0
ファイル: tests.py プロジェクト: 6ft/django
 def test_multiple_recipients(self):
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**', '*****@*****.**'])
     message = email.message()
     self.assertEqual(message['Subject'], 'Subject')
     self.assertEqual(message.get_payload(), 'Content')
     self.assertEqual(message['From'], '*****@*****.**')
     self.assertEqual(message['To'], '[email protected], [email protected]')
コード例 #6
0
ファイル: tests.py プロジェクト: 6ft/django
 def test_from_header(self):
     """
     Make sure we can manually set the From header (#9214)
     """
     email = EmailMessage('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], headers={'From': '*****@*****.**'})
     message = email.message()
     self.assertEqual(message['From'], '*****@*****.**')
コード例 #7
0
ファイル: tests.py プロジェクト: 6ft/django
    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>'))
コード例 #8
0
ファイル: views.py プロジェクト: imclab/storygame
def write(request, slug_story, activation_key, t='stories/write.html', d={}):
    story = get_object_or_404(Story, slug=slug_story)
    active_membership = story.active_membership()
    d['story']=story
    if not active_membership:
        story.turn_membership()
        return render(request, 'stories/done.html', d)
    membership = get_object_or_404(Membership, activation_key=activation_key)
    if active_membership.id != membership.id:
        return render(request, 'stories/done.html', d)
    new_line = Line(story=story)
    if request.POST:
        line_form=LineForm(request.POST, prefix='line', instance=new_line)
        if line_form.is_valid():
            line_form.save()
            next = story.turn_membership()
            mail_d = {
                'story': story,
                'site': get_current_site(request)
            }
            message = render_to_string('stories/email.txt', mail_d)
            email = EmailMessage(
                'Estas participando del concurso',
                message,
                to=[next.user.email])
            email.send()
            return render(request, 'stories/done.html', d)  
    else:
        line_form=LineForm(prefix='line')
    d = {
        'form': line_form,
        'story': story,
        'site': get_current_site(request)
    }
    return render(request, t, d)
コード例 #9
0
ファイル: views_v13.py プロジェクト: andrewlchen/careerhoot
def request_access(request, requester=None, requestee=None):

	# send_mail('Subject here', 'Here is the message.', '*****@*****.**', ['*****@*****.**'], fail_silently=False)


	'''
	- need to flag the requester as having requested a specific group
	- need to capture name, email, username, group name, group_pk
	- how do I capture the target recipient's email to populate in the "to" field 
	'''
	show_this_group = request.session['show_this_group']

	requester_name = '%s %s' % (User.objects.get(username=requester).first_name, User.objects.get(username=requester).last_name)
	requester_email = User.objects.get(username=requester).email
	requester_username = User.objects.get(username=requester).username
	requested_group_name = Group.objects.get(name=show_this_group)
	requested_group_pk = requested_group_name.id



	message = EmailMessage('Approve access for %s - %s' % (requester_name, requester_email), 'Click this link ____ to approve access for %s (%s, %s) to the group %s at primary key %s.' % (requester_name, requester_username, requester_email, requested_group_name, requested_group_pk), '*****@*****.**', [], ['*****@*****.**'])

	message.send()

	return HttpResponseRedirect('/introkick/home')
コード例 #10
0
ファイル: tasks.py プロジェクト: annax/filmfest.by
    def run(self, submission, template_code):
        logger.info('SendEmailFromTemplate:%d template %s' % (
                submission.id, template_code
        ))
        
        try:
            translation.activate(submission.submission_language)

            letter = LetterTemplate.objects.language().get(code=template_code)
            email = EmailMessage(
                letter.subject,
                letter.text % {'name': submission.applicant},
                '*****@*****.**',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '*****@*****.**'}
            )
            email.send()
        except:
            logger.info('SendEmailFromTemplate:%d template %s exception' % (
                submission.id, template_code
            ))
            raise
        finally:
            translation.deactivate()
        logger.info('SendEmailFromTemplate:%d template %s done' % (
            submission.id, template_code
        ))
コード例 #11
0
def contact(request):
    form_class = ContactForm

    # new logic!
    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            form_content = form.cleaned_data['content']

            # email the profile with the contact info
            template = get_template('contact_template.txt')

            context = Context({
                'contact_name': contact_name,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)

            email = EmailMessage(
                'New contact form submission',
                content,
                'Your website <*****@*****.**>',
                ['*****@*****.**'],
                headers = {'Reply-To': contact_email }
            )
            email.send()
            return redirect('contact')

    return render(request, 'contact.html', {
        'form': form_class,
    })
コード例 #12
0
def send_response(original_message, message_text, recipient_email, cc=None):
    """
    Helper function which sends an email message in response to a control
    message.

    :param original_message: The received control message.
    :type original_message: :py:class:`email.message.Message` or an object with
        an equivalent interface
    :param message_text: The text which should be included in the body of the
        response.
    :param cc: A list of emails which should receive a CC of the response.
    """
    subject = original_message.get('Subject')
    if not subject:
        subject = 'Your mail'
    message = EmailMessage(
        subject='Re: ' + subject,
        to=[original_message['From']],
        cc=cc,
        from_email=DISTRO_TRACKER_BOUNCES_EMAIL,
        headers={
            'From': DISTRO_TRACKER_CONTACT_EMAIL,
            'X-Loop': DISTRO_TRACKER_CONTROL_EMAIL,
            'References': ' '.join((original_message.get('References', ''),
                                    original_message.get('Message-ID', ''))),
            'In-Reply-To': original_message.get('Message-ID', ''),
        },
        body=message_text,
    )

    logger.info("control => %(to)s %(cc)s", {
        'to': recipient_email,
        'cc': " ".join(cc) if cc else "",
    })
    message.send()
コード例 #13
0
ファイル: tasks.py プロジェクト: annax/filmfest.by
    def run(self, submission):
        logger.info('SendSubmissionEmail for submission %s' % (
            submission.id
        ))
        try:
            translation.activate(submission.submission_language)

            email = EmailMessage(
                'Cinema Perpetuum Mobile 2013',
                self.get_email_message(submission),
                '*****@*****.**',
                [submission.applicant_email],
                list(settings.MAIL_BCC_LIST),
                headers = {'Reply-To': '*****@*****.**'})

            email.attach(
                'cpm2013.pdf', self.create_pdf(submission), 'application/pdf'
            )

            email.send()
        except:
            logger.exception('')
            raise
        finally:
            translation.deactivate()
            try:
                submission = Submission.objects.get(pk=submission.pk)
            except Submission.DoesNotExist:
                logger.exception('Failed to update "email sent" status')
            else:
                submission.comment_email_sent = True
                submission.save()
コード例 #14
0
ファイル: tasks.py プロジェクト: devangmundhra/alltoez
def send_bookmark_reminder_email():
    for profile in UserProfile.objects.all():
        user = profile.user
        # Get all bookmarked events ending in the next 7 days from today
        # What day will it be 7 days from now-
        now = timezone.now().date()
        seven_days = now + timedelta(days=7)
        my_bookmarks = Bookmark.objects.filter(user=user, event__end_date__gte=now, event__end_date__lte=seven_days)

        if my_bookmarks:
            bookmarked_events = []

            for bookmark in my_bookmarks:
                bookmarked_events.append({"EVENT_TITLE": bookmark.event.title,
                                     "IMAGE_URL": bookmark.event.image.url,
                                     "EVENT_DESCRIPTION": bookmark.event.description,
                                     "EVENT_URL": "http://www." + Site.objects.get_current().domain + bookmark.event.get_absolute_url(),
                                     "END_DATE": "{}".format(bookmark.event.end_date.strftime("%A, %d. %B"))})
            subject = "Events ending soon on Alltoez"

            msg = EmailMessage(subject=subject, from_email=("Alltoez", "*****@*****.**"),
                               to=[user.email])
            msg.template_name = "Bookmarked Events Ending"
            msg.global_merge_vars = {
                "USER_NAME": profile.first_name,
                "events": bookmarked_events,
            }
            msg.send()
コード例 #15
0
ファイル: views.py プロジェクト: xentry/django-lfs
def server_error(request):
    """Own view in order to pass RequestContext and send an error message.
    """
    exc_type, exc_info, tb = sys.exc_info()
    response = "%s\n" % exc_type.__name__
    response += "%s\n" % exc_info
    response += "TRACEBACK:\n"
    for tb in traceback.format_tb(tb):
        response += "%s\n" % tb

    if hasattr(request, 'user') and request.user:
        response += "User: %s\n" % request.user.username

    response += "\nREQUEST:\n%s" % request

    try:
        from_email = settings.ADMINS[0][1]
        to_emails = [a[1] for a in settings.ADMINS]
    except IndexError:
        pass
    else:
        mail = EmailMessage(
            subject="Error LFS", body=response, from_email=from_email, to=to_emails)
        mail.send(fail_silently=True)

    t = loader.get_template('500.html')
    return HttpResponseServerError(t.render(RequestContext(request)))
コード例 #16
0
ファイル: views.py プロジェクト: ozgurlukicin/ozgurlukicin
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())
コード例 #17
0
ファイル: user_profile.py プロジェクト: andressrg/swmanager
def send_invitation_key(sender, invitation, **kwargs):
    from django.core.mail import EmailMessage
    body = """
    Hello there,

    This is an invitation to be part of the {group_name} group on a StartupWeekend event.

    Click on the following link to activate your Startup Weekend Manager account:
    
    http://localhost:8000/#!/user/registration?email={email}&code={code}
    

    Best of lucks on th event, and remember: Stop talk, more action!


    --
    Startup Weekend Team
    """.format(group_name=invitation.to.name, email=invitation.email, code=invitation.key)

    print body
    
    msg = EmailMessage(subject="[swmanager] Invitation to an swmanager event",
                         body=body,
                         to=[invitation.email])
                         #[email protected])
    print "msg : %s" % msg
    print msg.send()
    print "######## Invitation key: %s" % invitation.key
コード例 #18
0
def send_mail_task(subject, message, to, only_print=False, history_line=None, headers=None):
    if not isinstance(to, (list, tuple)):
        to = [to]

    to = [t for t in to if t is not None]

    to = list(set(to)) # remove duplicates
    if history_line is not None:
        if headers is None:
            headers = {}
        history_header = '<%s>' % history_line
        headers['In-Reply-To'] = history_header
        headers['References'] = history_header

    if settings.EPO_EMAIL_ONLY_PRINT or only_print:
        info(u'printing portal email to: %s: %s (%r)\n%s', to, subject, headers, message)
    else:

        info('sending email to: %s', to)
        try:
            email_message = EmailMessage(subject, message, settings.SMTP_CONF["from"], to)
            if headers is not None:
                email_message.extra_headers = headers
            email_message.send()
        except Exception as e:
            error('failed to send email: %s', e)
            raise
コード例 #19
0
ファイル: views.py プロジェクト: giftyofori/smsreportcard
def sendemail(request , id ):
    """
    For send emails toa partitcular student parents
    """
    print request.path
    p = request.POST
    student = Student.objects.get(id = id)
    studentemail = "*****@*****.**" #str(student.Email)
    if request.method == 'GET':
        emailform = Emailform()

    if request.method =='POST':
        emailform = Emailform(request.POST)
        if emailform.is_valid():
            subject = p.get('subject','')
            body = p.get('body','')
            emailsubject = "%(subprfx)s %(subject)s" % {'subprfx':subprfx , 'subject':subject}
            try:
                email = EmailMessage(emailsubject,body,"*****@*****.**",['*****@*****.**',])
                email.send()
                print "Email sent"
            except:
                print "Msg not sent"
            try:    
                Email.objects.create(student = student , subject = subject ,body = body, sent_by=request.user)
            except:
                print "Email was not saves"
            return HttpResponse("Msg Sent")
    return render_to_response('msgs/sendmsg.html', dict(student = student ,emailform = emailform , user = request.user ,action="email"))
コード例 #20
0
ファイル: helpers.py プロジェクト: AstroMatchDynamics/MyJobs
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
コード例 #21
0
ファイル: email.py プロジェクト: guyt101z/openerp-esale
def SaleOrderEmail(order):
    """
    Send email Order
    order Int (ID)
    Return True/False
    """

    conn = connOOOP()
    shop = conn.SaleShop.get(OERP_SALE)

    context = {}
    context['active_id'] = shop.email_sale_order.id
    values = [
        [], #ids
        order, #rel_model_ref
        context, #context
    ]
    body_template = conn_webservice('poweremail.preview','on_change_ref', values)

    customer_email = body_template['value']['to']
    
    if customer_email != 'False':
        subject = body_template['value']['subject']
        body = body_template['value']['body_text']
        email = EmailMessage(subject, body, EMAIL_FROM, to=[customer_email], headers = {'Reply-To': EMAIL_REPPLY})

        try:
            email.send()
            return True
        except:
            error = _("Your order is in process but we don't send email. Check in your order customer section.")
            return False
コード例 #22
0
ファイル: models.py プロジェクト: emoitzi/django-excel-viewer
    def send_editor_mail(self):
        """
        Send notification mails to all users in group editor.
        Only send if ChangeRequest is not yet accepted
        :return:
        """
        if self.status == ChangeRequest.PENDING:
            editors = User.objects.filter(groups__name='editor')

            body = render_to_string('frontend/email/new_change_request.txt',
                                    {
                                        'change_request': self,
                                        'document_url': self.document_url()
                                    })

            bcc = []
            for editor in editors:
                bcc.append(get_user_email(editor))

            email = EmailMessage(_("New change request", ),
                                 body,
                                 bcc=bcc)
            email.send()
            logger.info("Sent change request notification mail to editors",
                        extra={
                            'body': body,
                            'bcc': bcc,
                        })
コード例 #23
0
    def do_email_reply(self, comment, content_object, request):
        """Send email notification of a new comment to the authors of
        the previous comments when email notifications have been requested."""
        exclude_list = self.mail_comment_notification_recipients + \
                       [author.email
                        for author in content_object.authors.all()] + \
                       [comment.email]
        recipient_list = set([comment.email
                              for comment in content_object.comments
                              if comment.email]) - \
                              set(exclude_list)

        if recipient_list:
            site = Site.objects.get_current()
            template = loader.get_template('comments/comment_reply_email.txt')
            context = Context({'comment': comment, 'site': site,
                               'protocol': PROTOCOL,
                               'content_object': content_object})
            subject = _('[%(site)s] New comment posted on "%(title)s"') % \
                      {'site': site.name,
                       'title': content_object.title}
            message = template.render(context)
            mail = EmailMessage(subject, message,
                                settings.DEFAULT_FROM_EMAIL,
                                bcc=recipient_list)
            mail.send(fail_silently=not settings.DEBUG)
コード例 #24
0
ファイル: forms.py プロジェクト: juslop/django_email_user
 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
コード例 #25
0
    def send_mail(self, form, files=[]):
        form_data = self.get_form_data(form)
        message = self.compile_message(form_data)
        context_dict = self.get_form_data_dict(form_data)

        import re
        mail_to = re.compile('\s*[,;]+\s*').split(self.mail_to)
        for key, email in enumerate(mail_to):
            mail_to[key] = self.string_template_replace(email, context_dict)

        mail_from = self.mail_from or None
        if mail_from:
            mail_from = self.string_template_replace(mail_from, context_dict)

        if self.mail_subject:
            mail_subject = self.string_template_replace(self.mail_subject, context_dict)
        else:
            mail_subject = self.title

        import logging
        logging.debug('Mail: '+repr(mail_from)+' --> '+repr(mail_to));

        from django.core.mail import EmailMessage
        message = EmailMessage(mail_subject, message, mail_from or None, mail_to)

        if self.mail_uploaded_files:
            for file_path in files:
                message.attach_file(file_path)

        message.send(fail_silently=False)
コード例 #26
0
 def send(self, **kwargs):
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     signup_url = u"%s://%s%s?%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_signup"),
         urllib.urlencode({"code": self.code})
     )
     ctx = {
         "signup_code": self,
         "current_site": current_site,
         "signup_url": signup_url,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/invite_user_subject.{0}".format(ext), ctx)
     message = render_to_string(
         "account/email/invite_user.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signup_code_sent.send(sender=SignupCode, signup_code=self)
コード例 #27
0
 def send(self, **kwargs):
     current_site = kwargs["site"] if "site" in kwargs else Site.objects.get_current()
     protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
     activate_url = u"%s://%s%s" % (
         protocol,
         unicode(current_site.domain),
         reverse("account_confirm_email", args=[self.key])
     )
     ctx = {
         "email_address": self.email_address,
         "user": self.email_address.user,
         "activate_url": activate_url,
         "current_site": current_site,
         "key": self.key,
     }
     ext = "html" if settings.EMAIL_CONTENT_HTML else "txt"
     subject = render_to_string(
         "account/email/email_confirmation_subject.{0}".format(ext), ctx)
     subject = "".join(subject.splitlines())  # remove superfluous line breaks
     message = render_to_string(
         "account/email/email_confirmation_message.{0}".format(ext), ctx)
     msg = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email_address.email])
     if settings.EMAIL_CONTENT_HTML:
         msg.content_subtype = "html"
     msg.send()
     self.sent = timezone.now()
     self.save()
     signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)
コード例 #28
0
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)
コード例 #29
0
ファイル: email.py プロジェクト: brenotx/SIGI-1.6
def enviar_email(from_email, subject, template, tags):
    """Envia o email para o destinatário definido, a partir do template
    definido para ser renderizado. Os argumentos são:
        * from_email - Email do remetente
        * subject - Assunto da Mensagem
        * template - Template que será usado para gerar o corpo
        da mensagem
        * tags - Variáveis de contexto para ser renderizado no
        template.
    """
    if from_email is None:
        raise ValueError("Insira o email do remetente.")
    elif subject is None:
        raise ValueError("Insira o assunto da mensagem.")
    elif template is None:
        raise ValueError(u"Template da mensagem não encontrado")
    elif tags is None:
        raise ValueError("Insira o conteúdo da mensagem.")

    # Gerando a mensagem
    mensagem = render_to_string(template, tags)

    # Enviando a mensagem
    email = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + " " + subject, mensagem,
        from_email, [from_email])
    email.send()
コード例 #30
0
ファイル: models.py プロジェクト: emoitzi/django-excel-viewer
    def send_new_status_notification_mail(self):
        subject, body = "", ""
        if self.status == ChangeRequest.ACCEPTED:
            subject = _("Your change request has been accepted")
            body = render_to_string(
                'frontend/email/change_request_accepted.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })
        if self.status == ChangeRequest.DECLINED:
            subject = _("Your change request has been declined")
            body = render_to_string(
                'frontend/email/change_request_declined.txt',
                {
                    'change_request': self,
                    'document_url': self.document_url()
                })

        to = get_user_email(self.author)
        email = EmailMessage(subject,
                             body,
                             to=[to])
        email.send(fail_silently=True)
        logger.info("Sent change request status notification mail to author",
                    extra={
                        'body': body,
                        'to': to,
                    })
コード例 #31
0
ファイル: auth.py プロジェクト: vain01/relate
def reset_password(request, field="email"):
    if not settings.RELATE_REGISTRATION_ENABLED:
        raise SuspiciousOperation(
                _("self-registration is not enabled"))

    # return form class by string of class name
    ResetPasswordForm = globals()["ResetPasswordFormBy" + field.title()]  # noqa
    if request.method == "POST":
        form = ResetPasswordForm(request.POST)
        user = None
        if form.is_valid():
            exist_users_with_same_email = False
            if field == "instid":
                inst_id = form.cleaned_data["instid"]
                try:
                    user = get_user_model().objects.get(
                            institutional_id__iexact=inst_id)
                except ObjectDoesNotExist:
                    pass

            if field == "email":
                email = form.cleaned_data["email"]
                try:
                    user = get_user_model().objects.get(email__iexact=email)
                except ObjectDoesNotExist:
                    pass
                except MultipleObjectsReturned:
                    exist_users_with_same_email = True

            if exist_users_with_same_email:
                # This is for backward compatibility.
                messages.add_message(request, messages.ERROR,
                        _("Failed to send an email: multiple users were "
                          "unexpectedly using that same "
                          "email address. Please "
                          "contact site staff."))
            else:
                if user is None:
                    FIELD_DICT = {  # noqa
                            "email": _("email address"),
                            "instid": _("institutional ID")
                            }
                    messages.add_message(request, messages.ERROR,
                            _("That %(field)s doesn't have an "
                                "associated user account. Are you "
                                "sure you've registered?")
                            % {"field": FIELD_DICT[field]})
                else:
                    if not user.email:
                        messages.add_message(request, messages.ERROR,
                                _("The account with that institution ID "
                                    "doesn't have an associated email."))
                    else:
                        email = user.email
                        user.sign_in_key = make_sign_in_key(user)
                        user.save()

                        from relate.utils import render_email_template
                        message = render_email_template(
                            "course/sign-in-email.txt", {
                                "user": user,
                                "sign_in_uri": request.build_absolute_uri(
                                    reverse(
                                        "relate-reset_password_stage2",
                                        args=(user.id, user.sign_in_key,))),
                                "home_uri": request.build_absolute_uri(
                                    reverse("relate-home"))
                            })
                        from django.core.mail import EmailMessage
                        msg = EmailMessage(
                                string_concat("[%s] " % _(get_site_name()),
                                              _("Password reset")),
                                message,
                                getattr(settings, "NO_REPLY_EMAIL_FROM",
                                        settings.ROBOT_EMAIL_FROM),
                                [email])

                        from relate.utils import get_outbound_mail_connection
                        msg.connection = (
                                get_outbound_mail_connection("no_reply")
                                if hasattr(settings, "NO_REPLY_EMAIL_FROM")
                                else get_outbound_mail_connection("robot"))
                        msg.send()

                        if field == "instid":
                            messages.add_message(request, messages.INFO,
                                _("The email address associated with that "
                                  "account is %s.")
                                % masked_email(email))

                        messages.add_message(request, messages.INFO,
                                _("Email sent. Please check your email and "
                                  "click the link."))

                        return redirect("relate-home")
    else:
        form = ResetPasswordForm()

    return render(request, "reset-passwd-form.html", {
        "field": field,
        "form_description":
            _("Password reset on %(site_name)s")
            % {"site_name": _(get_site_name())},
        "form": form
        })
コード例 #32
0
 def delete_model(self, request, obj):
     EmailMessage('Greetings from a deleted object',
                  'I hereby inform you that some user deleted me',
                  '*****@*****.**', ['*****@*****.**']).send()
     return super().delete_model(request, obj)
コード例 #33
0
    def xconvert(self, sourcefile, targetfile):
        """Convert video to mp4 format"""

        errormsg = ""

        # ffmpeg command options:
        #  -y  answer yes to all queries
        #  -v -1 be less verbose
        # -i sourcefile   input file
        # -f flv  output format is flv
        # -an no audio in output
        # -s geometry set size of output
        #
        # new options for conversion to h264/mp4
        # ffmpeg -v -1 -i $1 -an -vcodec libx264 -vpre hq -crf 22 -threads 0 $1:r.mp4
        #
        ffmpeg = [
            settings.FFMPEG_PROGRAM, "-y", "-v", "-1", "-i", sourcefile,
            "-vcodec", "libx264", "-an", "-vpre", "hq", "-crf", "22",
            "-threads", "0", targetfile
        ]

        debug(" ".join(ffmpeg))

        process = Popen(ffmpeg, stdout=PIPE, stderr=PIPE)
        start = time.time()

        while process.poll() == None:
            if time.time() - start > settings.FFMPEG_TIMEOUT:
                # we've gone over time, kill the process
                os.kill(process.pid, signal.SIGKILL)
                debug("Killing ffmpeg process")
                errormsg = "Conversion of video took too long.  This site is only able to host relatively short videos."

        status = process.poll()
        #out,err = process.communicate()

        # Check if file exists and is > 0 Bytes
        try:
            s = os.stat(targetfile)
            fsize = s.st_size
            if (fsize == 0):
                os.remove(targetfile)
                errormsg = "Conversion of video failed: please try to use a diffent format"
        except:
            errormsg = "Conversion of video failed: please try to use a different video format"

        if errormsg:
            # we have a conversion error
            # notify the admins, attaching the offending file
            msgtxt = "Error: %s\n\nCommand: %s\n\n" % (errormsg,
                                                       " ".join(ffmpeg))

            message = EmailMessage("Video conversion failed",
                                   msgtxt,
                                   to=[a[1] for a in settings.ADMINS])
            message.attach_file(sourcefile)
            message.send(fail_silently=False)

            # and raise a validation error for the caller
            raise ValidationError(errormsg)
コード例 #34
0
ファイル: views.py プロジェクト: sanyam1992000/DHA
def StationExitView(request, station_no):
    if request.method == 'POST':
        try:
            entry = request.POST.get("first")
            entry = int(entry)
            return redirect('core:station_entry', entry)
        except:
            pass

        try:
            exit = request.POST.get("second")
            exit = int(exit)
            return redirect('core:station_exit', exit)
        except:
            pass
    station = models.Station.objects.get(station_no=station_no)
    pics = list(models.Person.objects.all().values_list('pic', flat=True))
    known_face_names = list(models.Person.objects.all().values_list('name', flat=True))
    uids = list(models.Person.objects.all().values_list('uid', flat=True))
    known_face_encodings = []
    for pic in pics:
        # print(pic)
        image = face_recognition.load_image_file(os.path.join(base_dir, str(pic)))
        image_encoding = face_recognition.face_encodings(image)[0]
        known_face_encodings.append(image_encoding)

    i = 0

    video_capture = cv2.VideoCapture(0)
    face_locations = []
    face_encodings = []
    face_names = []
    face_uids = []
    process_this_frame = True

    while True:
        # Grab a single frame of video
        ret, frame = video_capture.read()

        try:
            # Resize frame of video to 1/4 size for faster face recognition processing
            small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

            # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
            rgb_small_frame = small_frame[:, :, ::-1]

            # Only process every other frame of video to save time
            if process_this_frame:
                # Find all the faces and face encodings in the current frame of video
                face_locations = face_recognition.face_locations(rgb_small_frame)
                face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

                face_names = []
                face_uids = []
                for face_encoding in face_encodings:
                    # See if the face is a match for the known face(s)
                    matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.5)
                    name = "Unknown"
                    uid = -1
                    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                    best_match_index = np.argmin(face_distances)
                    if matches[best_match_index]:
                        name = known_face_names[best_match_index]
                        uid = uids[best_match_index]
                        person = models.Person.objects.get(name=name)
                        try:
                            log = models.Log.objects.get(person=person, status=0)
                            log.exit_station = station
                            log.exit_datetime = timezone.now()
                            log.status = 1
                            log.fare = 20
                            log.save()
                            try:
                                subject = 'Thanks for Travelling in Yugant Express'
                                message = person.name + ', thanks for travelling.\n From Station : {} \n Entry time : {} \n To station : {}\n Exit Time : {} \n Your Fare : {}'.format(
                                    log.entry_station, log.entry_datetime, log.exit_station, log.exit_datetime, log.fare)
                                from_email = settings.EMAIL_HOST_USER
                                to_email = [person.email]
                                email = EmailMessage(subject=subject, from_email=from_email, to=to_email, body=message)
                                email.send()
                                # print('email sent')
                            except:
                                # print('failed to send email')
                                pass
                        except:
                            # print('Chada hi nhi tha... cheating krta h yeh !! fine lo')
                            pass
                    # print(name)
                    face_names.append(name)
                    face_uids.append(uid)
            i += 1
            process_this_frame = not process_this_frame

            # Display the results
            for (top, right, bottom, left), name, uid in zip(face_locations, face_names, face_uids):
                # Scale back up face locations since the frame we detected in was scaled to 1/4 size
                top *= 4
                right *= 4
                bottom *= 4
                left *= 4

                # Draw a box around the face
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

                # Draw a label with a name below the face
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, str(name + ':'+ str(uid)), (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        except:
            # print("Cannot read frame")
            pass
        # Display the resulting image
        cv2.imshow('Video', frame)

        # Hit 'q' on the keyboard to quit!
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release handle to the webcam
    video_capture.release()
    cv2.destroyAllWindows()

    return render(request, 'core/index.html')
コード例 #35
0
django.setup()

from jp2_to_tiff_conversion import jp2_to_tiff
from model_call import ModelCaller
from sentinel_download import SentinelDownload
from upload_to_mapbox import start_upload

if __name__ == '__main__':
    try:
        sentinel_downloader = SentinelDownload()
        sentinel_downloader.process_download()
        sentinel_downloader.executor.shutdown()

        model_caller = ModelCaller()
        model_caller.start()

        jp2_to_tiff()
        uploader = start_upload()

        uploader.shutdown()
        model_caller.executor.shutdown()
    except Exception as error:
        EmailMessage(
            subject='Pep download issue',
            body=
            (f'Daemon can not download Sentinel2 data. Issue information listed bellow: '
             f'\n\n{str(error)}\n\n {"".join(traceback.format_tb(error.__traceback__))}'
             ),
            from_email=settings.EMAIL_HOST_USER,
            to=settings.EMAIL_ADMIN_MAILS).send()
コード例 #36
0
def dna_extraction():
    q = "start c=node(*) match (c)-[:hasChild]->(cc) where c.entity ='C' and cc.entity='C' return id(cc), cc.genid"
    print "Retrieving mice to exclude from aliquot extraction..."
    mice_to_exclude = set(find_mice_to_exclude())
    print "Retrieving cases..."
    cq = neo4j.CypherQuery(gdb, q)
    cases = cq.execute()
    print len(cases), " case(s) found"

    for c in cases:
        case_id = c[0]
        case_gid = c[1]
        gid = GenealogyID(case_gid)
        if gid.getOrigin() == 'CRC' and int(gid.getCaseCode()) <= 430:
            continue
        print "===[ Case %s ]====================" % case_gid
        check_case(case_id, case_gid)
        print ""

    print ""
    print "Aliquots for extraction (%d):" % len(rl_aliquots)
    rl = sorted(rl_aliquots)
    al_recent, al_old = sortAliquots(rl_aliquots)

    recipients = []
    sender = ''
    subject = 'Aliquots for DNA Extraction'

    text_content = ""
    #text_content = "Red Node = Aliquot selected for extraction\nBlue Border = DNA already extracted\nBox Shape = RNAlater aliquots present\n\n"
    text_content = text_content + "Recent aliquots (" + (
        datetime.now() - timedelta(days=days_recent)
    ).strftime("%a, %d %b %Y") + " - " + datetime.now().strftime(
        "%a, %d %b %Y") + "): " + str(len(al_recent)) + "\n"

    for a in al_recent:
        #urlimg = ""
        #if aliquots.index(a) != 0:
        #
        #    if a[:9] == aliquots[aliquots.index(a)-1][:9]:
        #        urlimg = ""
        #
        #    else:
        #        urlimg = ' http://devircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png'
        #else:
        #    urlimg = ' http://devircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png'
        #urlimg = ' http://lasircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png'

        #text_content = text_content + a + urlimg + '\n'
        text_content = text_content + a + '\n'

    text_content = text_content + "\nOlder aliquots: " + str(
        len(al_old)) + "\n"

    for a in al_old:
        #urlimg = ' http://lasircc.polito.it/tree_images/'+ a[:9] +'00000000000000000.png'
        #text_content = text_content + a + urlimg + '\n'
        text_content = text_content + a + '\n'

    print ""
    print "Sending email"
    print "Recipients: ", ", ".join(recipients)
    print "Content:"
    cprint(text_content, 'cyan')

    try:
        e = EmailMessage(subject=subject,
                         body=text_content,
                         from_email=sender,
                         to=recipients)
        e.attach(filename="Recent_aliquots.las",
                 mimetype="text/plain",
                 content='\n'.join(al_recent))
        e.attach(filename="Old_aliquots.las",
                 mimetype="text/plain",
                 content='\n'.join(al_old))
        e.send()
        print
        print 'Email sent'
    except Exception, e:
        print e
        cprint('Error sending email', 'red')
コード例 #37
0
def create():
    single_events = []
    multiple_events = []
    a = list(Events.objects.all())
    print(a)
    for i in a:
        print(i.name, i.contact_email1, i.contact_email2)
        if i.max_participants > 1:
            b = list(event_register.objects.filter(event_name=i.name))
            e = []
            for j in b:
                c = []
                c.append(j.team_name)
                d = list(
                    Team_details.objects.filter(event_name=i.name,
                                                team_name=j.team_name))
                for k in d:
                    c.append(k.name)
                    c.append(k.email)
                    c.append(k.phone)
                for l in range(len(d), i.max_participants):
                    c.append("")
                    c.append("")
                    c.append("")
                ps = list(Payment_Status.objects.all())
                flag = 0
                for ps1 in ps:
                    if ps1.username == j.username:
                        c.append(ps1.payment)
                        flag = 1
                if flag == 0:
                    c.append("NO")
                e.append(c)
            labels = ["Team Name"]
            for k in range(0, i.max_participants):
                labels.append("Member" + str(k + 1) + "Name")
                labels.append("Member" + str(k + 1) + "Email")
                labels.append("Member" + str(k + 1) + "Phone")
            labels.append("Payment_Status")
            df = pa.DataFrame(e, columns=labels)
            df.to_csv(i.name + ".csv")
            subject = "Registration File"
            body = u"Find the attached CSV File for registered participants for your event " + i.name
            to = [
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**', '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**', '*****@*****.**',
                '*****@*****.**'
            ]
            # to = []
            # to.append(i.contact_email1)
            # to.append(i.contact_email2)
            emailsend = EmailMessage(subject, body, to=to)
            path = os.getcwd()
            path += "/" + i.name + ".csv"
            multiple_events.append(path)
            emailsend.attach_file(path)
            emailsend.send()
        else:
            labels = [
                'Name', 'Email', 'Username', 'College Name', 'Contact Number',
                'Gender', 'Payment Status'
            ]
            labels1 = [
                'Event Name', 'Name', 'Email', 'Username', 'College Name',
                'Contact Number', 'Gender', 'Payment Status'
            ]
            b = list(single_event.objects.filter(event_name=i.slug))
            e = []
            h = []
            o = []
            for j in b:
                f = []
                h = []
                c = list(User.objects.all())
                for k in c:
                    if k.username == j.username:
                        break
                d = list(UserProfile.objects.filter(user=k))
                for l in d:
                    h.append(i.name)
                    f.append(l.name)
                    f.append(k.email)
                    f.append(k.username)
                    f.append(l.college)
                    f.append(l.contact)
                    if l.gender == '0':
                        f.append("Female")
                    elif l.gender == '1':
                        f.append("Male")
                    elif l.gender == '2':
                        f.append("Other")
                h += f
                ps = list(Payment_Status.objects.all())
                flag = 0
                for ps1 in ps:
                    if ps1.username == j.username:
                        f.append(ps1.payment)
                        h.append(ps1.payment)
                        flag = 1
                if flag == 0:
                    f.append("NO")
                    h.append("NO")
                o.append(h)
                e.append(f)
            g = []
            for m in e:
                if len(m) > 0:
                    g.append(m)
            for m in o:
                if len(m) > 0:
                    single_events.append(m)
            df = pa.DataFrame(g, columns=labels)
            df.to_csv(i.name + ".csv")
            subject = "Registration File"
            body = u"Find the attached CSV File for registered participants for single events "
            to = [
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**', '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**',
                '*****@*****.**', '*****@*****.**',
                '*****@*****.**'
            ]
            # to.append(i.contact_email1)
            # to.append(i.contact_email2)
            emailsend = EmailMessage(subject, body, to=to)
            path = os.getcwd()
            path += ("/" + i.name + ".csv")
            emailsend.attach_file(path)
            emailsend.send()
    df = pa.DataFrame(single_events, columns=labels1)
    df.to_csv("Single_Events.csv")
    subject = "Single Events Registration File"
    body = u"Find the attached CSV File for registered participants for single event"
    to = [
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**'
    ]
    emailsend = EmailMessage(subject, body, to=to)
    path = os.getcwd()
    path += "/Single_Events.csv"
    emailsend.attach_file(path)
    emailsend.send()
    subject = "Team Events Registration File"
    body = u"Find the attached CSV File for registered participants for team event"
    to = [
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**'
    ]
    emailsend = EmailMessage(subject, body, to=to)
    for fil in multiple_events:
        emailsend.attach_file(fil)
    emailsend.send()
コード例 #38
0
ファイル: utils.py プロジェクト: Anubhajain05/User-details
 def send_email(data):
     email= EmailMessage(
         subject=data['email_subject'],body= data['email_body'],to=[data['to_email']]
     )
     email.send()
コード例 #39
0
ファイル: email_logs.py プロジェクト: hp7017/RestPractice
from RestPractice import env
from django.core.mail import EmailMessage
import requests
from datetime import datetime
import django
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'RestPractice.settings'
django.setup()
username = env.USERNAME
token = env.TOKEN
paths = [
    'var/log/www.librarygenesis.in.server.log',
    'var/log/www.librarygenesis.in.error.log'
]
for path in paths:
    r = requests.get(
        f'https://www.pythonanywhere.com/api/v0/user/{username}/files/path/{path}',
        headers={'Authorization': 'Token {token}'.format(token=token)})
    date = datetime.now()
    date = date.strftime('%Y-%m-%d')
    lines = r.text.split('\n')
    today_lines = [line for line in lines if line.split(' ')[0] == date]
    today_data = '\n'.join(today_lines)
    email = EmailMessage(from_email='Django Server <*****@*****.**>',
                         to=['*****@*****.**'],
                         subject=f'Server Logs [{date}]',
                         body=f'{today_data}')
    email.send(fail_silently=False)
コード例 #40
0
ファイル: auth.py プロジェクト: vain01/relate
def sign_up(request):
    if not settings.RELATE_REGISTRATION_ENABLED:
        raise SuspiciousOperation(
                _("self-registration is not enabled"))

    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            if get_user_model().objects.filter(
                    username=form.cleaned_data["username"]).count():
                messages.add_message(request, messages.ERROR,
                        _("A user with that username already exists."))

            else:
                email = form.cleaned_data["email"]
                user = get_user_model()(
                        email=email,
                        username=form.cleaned_data["username"])

                user.set_unusable_password()
                user.status = user_status.unconfirmed
                user.sign_in_key = make_sign_in_key(user)
                user.save()

                from relate.utils import render_email_template
                message = render_email_template("course/sign-in-email.txt", {
                    "user": user,
                    "sign_in_uri": request.build_absolute_uri(
                        reverse(
                            "relate-reset_password_stage2",
                            args=(user.id, user.sign_in_key,))
                        + "?to_profile=1"),
                    "home_uri": request.build_absolute_uri(
                        reverse("relate-home"))
                    })

                from django.core.mail import EmailMessage
                msg = EmailMessage(
                        string_concat("[%s] " % _(get_site_name()),
                                      _("Verify your email")),
                        message,
                        getattr(settings, "NO_REPLY_EMAIL_FROM",
                                settings.ROBOT_EMAIL_FROM),
                        [email])

                from relate.utils import get_outbound_mail_connection
                msg.connection = (
                        get_outbound_mail_connection("no_reply")
                        if hasattr(settings, "NO_REPLY_EMAIL_FROM")
                        else get_outbound_mail_connection("robot"))
                msg.send()

                messages.add_message(request, messages.INFO,
                        _("Email sent. Please check your email and click "
                        "the link."))

                return redirect("relate-home")
        else:
            if ("email" in form.errors
                    and "That email address is already in use."
                    in form.errors["email"]):
                messages.add_message(request, messages.ERROR,
                        _("That email address is already in use. "
                        "Would you like to "
                        "<a href='%s'>reset your password</a> instead?")
                        % reverse(
                            "relate-reset_password"))

    else:
        form = SignUpForm()

    return render(request, "generic-form.html", {
        "form_description": _("Sign up"),
        "form": form
        })
コード例 #41
0
def register(request):
    if request.method == 'POST':
        first_name1 = request.POST['first_name']
        last_name1 = request.POST['last_name']
        username = request.POST['username']
        email1 = request.POST['email']
        password = request.POST['password']
        password2 = request.POST['password2']

        context = {'has_error': False}

        if username == '':
            messages.add_message(request, messages.ERROR,
                                 'Username is required')
            context['has_error']: True

        if first_name1 == '':
            messages.add_message(request, messages.ERROR,
                                 'Firstname is required')
            context['has_error']: True

        if last_name1 == '':
            messages.add_message(request, messages.ERROR,
                                 'Lastname is required')
            context['has_error']: True

        if email1 == '':
            messages.add_message(request, messages.ERROR, 'Email is required')
            context['has_error']: True

        if password == '':
            messages.add_message(request, messages.ERROR,
                                 'Password is required')
            context['has_error']: True

        if password2 == '':
            messages.add_message(request, messages.ERROR,
                                 'Confirm Password is required')
            context['has_error']: True

        # username should be under 15 characters
        if len(username) > 10:
            messages.add_message(request, messages.ERROR,
                                 'please Enter short username')
            context['has_error'] = True

        # username should be alphanumeric mens does not contain any &*()%$ etc..
        if not username.isalnum():
            messages.add_message(request, messages.ERROR,
                                 'Username Should Be Alphanumeric')
            context['has_error'] = True

        # Username Already exists or not if yes than show this error
        if User.objects.filter(username=username).exists():
            messages.add_message(request, messages.ERROR,
                                 'Username Already Exists')
            context['has_error'] = True

        # validate email or not
        if not validate_email(email1, check_regex=True, check_mx=True):
            messages.add_message(request, messages.ERROR,
                                 'please provide a valid Email')
            context['has_error'] = True

        # Email Already exists or not if yes than show this error
        if User.objects.filter(email=email1).exists():
            messages.add_message(request, messages.ERROR,
                                 'Email Already Exists')
            context['has_error'] = True

        # password should match
        if password != password2:
            messages.add_message(request, messages.ERROR, 'Password Not Match')
            context['has_error'] = True

        if len(password) < 7:
            messages.add_message(
                request, messages.ERROR,
                'password shod be Atleast 7 character or more')
            context['has_error'] = True

        # if remember1 == '':
        #     messages.add_message(request, messages.ERROR, 'Please Agree The Terms and Conditions.')
        #     context['has_error']: True

        if context['has_error']:
            return render(request, 'users/register.html', context, status=400)

        user = User.objects.create_user(username=username,
                                        email=email1,
                                        password=password)
        user.first_name = first_name1
        user.last_name = last_name1
        user.is_active = False
        user.save()
        # start here email verification online

        current_site = get_current_site(request)
        email_subject = 'Activate Your Account'
        message = render_to_string(
            'users/activate.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': generate_token.make_token(user),
            })

        email_message = EmailMessage(
            email_subject,
            message,
            settings.EMAIL_HOST_USER,
            [email1],
        )

        # email_message.send()
        EmailThread(email_message).start()

        messages.add_message(
            request, messages.SUCCESS,
            'We will share you mail to activate your account')
        return render(request, 'users/register.html')

    else:
        return render(request, 'users/register.html')
コード例 #42
0
    def post(self, request, pk):
        max_seats = Movie.objects.get(pk=pk).max_no_seats
        tickets = Ticket.objects.filter(movie=Movie.objects.get(pk=pk))
        shows = Show.objects.filter(movie__name=Movie.objects.get(pk=pk).name,
                                    show_time__gte=datetime.now())
        form = self.form_class(request.POST, mov_id=pk)
        if form.is_valid():
            ticket = form.save(commit=False)

            ticket.user = request.user
            ticket.movie = Movie.objects.get(pk=pk)
            ticket.price = ticket.show.price
            #Ticket numbers taken for the shows
            nos = []
            tis = Ticket.objects.filter(movie=Movie.objects.get(pk=pk),
                                        show=ticket.show)
            for t in tis:
                nos.append(t.seat_no)
            if ticket.seat_no in nos:
                form.add_error('seat_no', 'Seat Already taken')
                return render(
                    request, self.template_name, {
                        'form': form,
                        'seats': range(max_seats),
                        'tickets': tickets,
                        'shows': shows,
                        'ti': self.title
                    })
            cred = UserWallet.objects.get(user=request.user)
            if cred.credit - ticket.price < 0:
                form.add_error(
                    'seat_no',
                    'Please restock your account before Booking tickets')
                return render(
                    request, self.template_name, {
                        'form': form,
                        'seats': range(max_seats),
                        'tickets': tickets,
                        'shows': shows,
                        'ti': self.title
                    })
            cred.credit = cred.credit - ticket.price
            cred.save()

            ticket.theatre = Theatre.objects.get(pk=ticket.show.theatre_id)
            msg1 = 'Hi ' + str(
                ticket.user
            ) + '!\n\nYour ticket booking has been confirmed, with the following details : \n'
            msg2 = 'Movie : ' + str(ticket.movie) + '\nTheatre : ' + str(
                ticket.theatre) + '\nShow : ' + str(
                    ticket.show) + '\nSeat Number : ' + str(ticket.seat_no)
            msg3 = '\nPrice : Rs.' + str(ticket.price)
            msg4 = '\nRemaining Credit: Rs.' + str(cred.credit)
            msg5 = '\n\nThank you for choosing TheatriX, Enjoy your movie!'
            msg = msg1 + msg2 + msg3 + msg4 + msg5
            email = EmailMessage('Your tickets for ' + str(ticket.movie.name),
                                 msg, '*****@*****.**',
                                 [ticket.user.email])
            try:
                if email.send():
                    print "Email Sent"
                else:
                    print "Email Not sent"
            except Exception as e:
                print e
            ticket.save()
            return redirect('Movies:ticket_details', pk=ticket.pk)
        return render(
            request, self.template_name, {
                'form': form,
                'seats': range(max_seats),
                'tickets': tickets,
                'shows': shows,
                'ti': self.title
            })
コード例 #43
0
ファイル: email.py プロジェクト: tjnu1430130310/eBookRS
 def send_html_email(self, subject, html_content, to_list):
     """发送html邮件"""
     send_from = settings.DEFAULT_FROM_EMAIL
     msg = EmailMessage(subject, html_content, send_from, to_list)
     msg.content_subtype = "html"  # 设置类型为html
     msg.send()
コード例 #44
0
def payment_process(request):
    order_id = request.session.get('order_id')
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        # retrieve nonce
        nonce = request.POST.get('payment_method_nonce', None)
        # create and submit transaction
        result = braintree.Transaction.sale({
            'amount':
            '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce':
            nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            # mark the order as paid
            order.paid = True
            # store the unique transaction id
            order.braintree_id = result.transaction.id
            order.save()
            # create invoice e-mail
            subject = 'My Shop - Invoice no. {}'.format(order.id)
            message = 'Please, find attached the invoice for your recent purchase.'
            email = EmailMessage(subject, message, '*****@*****.**',
                                 [order.email])
            # generate PDF
            html = render_to_string('orders/order/pdf.html', {'order': order})
            out = BytesIO()
            stylesheets = [
                weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')
            ]
            weasyprint.HTML(string=html).write_pdf(out,
                                                   stylesheets=stylesheets)
            # attach PDF file
            email.attach('order_{}.pdf'.format(order.id), out.getvalue(),
                         'application/pdf')
            # send e-mail
            email.send()

            # send sms
            # Your Account SID from twilio.com/console
            #account_sid = "AC1cac4d02cc38ebe54d55d730ca00703c"
            # Your Auth Token from twilio.com/console
            #auth_token = "423946a57f6b878f341abe7d66b3fe2f"

            #client = Client(account_sid, auth_token)

            #message = client.messages.create(
            #	to="+14027066443",
            #	from_="+117122484584",
            #	body="Thank you {} {}, Your order {} has been placed successfully and will be delivered to {}, {}, {}".format(order.first_name,order.last_name,order.id,order.address,order.city,order.postal_code)
            #)
            #print(message.sid)

            client = nexmo.Client(key='afc1e627', secret='ddV43jqW79xSneKo')

            client.send_message({
                'from':
                '18595920844',
                'to':
                '14027066443',
                'text':
                'Thank you {} {}, Your order {} has been placed successfully and will be delivered to {}, {}, {}'
                .format(order.first_name, order.last_name, order.id,
                        order.address, order.city, order.postal_code)
            })

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')
    else:
        # generate token
        client_token = braintree.ClientToken.generate()
        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })
コード例 #45
0
def send_email():
    subject, from_email, to = 'Docker', '*****@*****.**', '*****@*****.**'
    text_content = f'Hi from docker'
    msg = EmailMessage(subject, text_content, from_email, [to])
    msg.send()
コード例 #46
0
ファイル: views.py プロジェクト: thiasB/isimip
def confirm_data(page, request, id):
    if not request.user.is_authenticated():
        messages.info(request,
                      'You need to be logged in to perform this action.')
        return HttpResponseRedirect('/dashboard/login/' +
                                    "?next={}".format(request.path))
    try:
        impact_model = ImpactModel.objects.get(id=id)
    except ImpactModel.DoesNotExist:
        messages.warning(request, 'Unknown model')
        return HttpResponseRedirect('/impactmodels/')
    if not (impact_model.base_model in request.user.userprofile.owner.all()
            or request.user.is_superuser):
        messages.info(request,
                      'You need to be logged in to perform this action.')
        nexturl = reverse('wagtailadmin_login') + "?next={}".format(
            request.path)
        return HttpResponseRedirect(nexturl)
    if not impact_model.can_confirm_data():
        messages.warning(
            request,
            'Data confirmation for this model is not possible at the moment.')
        return HttpResponseRedirect('/impactmodels/')
    confirmation = impact_model.confirmation
    if request.method == 'GET':
        title = 'Confirm data for : %s' % impact_model
        subpage = {'title': title, 'url': ''}
        context = {
            'page': page,
            'subpage': subpage,
            'user': request.user,
            'simulation_round': impact_model.simulation_round,
            'sector': impact_model.base_model.sector,
            'impact_model_name': impact_model.base_model.name,
            'custom_text': confirmation.email_text,
            'impact_model_url': '/impactmodels/edit/%s/' % impact_model.pk,
        }

        template = 'climatemodels/confirm_data.html'
        return render(request, template, context)
    elif request.method == 'POST':
        # raise Exception(request.POST)
        form = DataConfirmationForm(request.POST)
        if not form.is_valid():
            if 'license' in form.cleaned_data:
                messages.error(
                    request,
                    'You need to confirm that your impact model is correct and complete!'
                )
            else:
                messages.error(request, 'You need to select a valid license!')
            return HttpResponseRedirect(request.path)
        license = form.cleaned_data['license']
        if license == 'other' and form.cleaned_data['other_license_name'] == '':
            messages.error(
                request,
                'If you choose the "Other" license you need to fill out the name!'
            )
            return HttpResponseRedirect(request.path)
        # build and send confirm email
        confirm_email = DataPublicationConfirmation.for_site(request.site)
        license = license == 'other' and form.cleaned_data[
            'other_license_name'] or license
        context = {
            'model_contact_person': request.user.get_full_name(),
            'simulation_round': impact_model.simulation_round,
            'impact_model_name': confirmation.impact_model.base_model.name,
            'custom_text': confirmation.email_text,
            'license': license,
        }
        confirm_body = Template(confirm_email.body)
        confirm_body = confirm_body.render(Context(context))
        # add newlines to the end of body to split attachment from text
        confirm_body += "\n\n"
        ccs = impact_model.base_model.impact_model_owner.exclude(
            pk=request.user.pk)
        pdf = render_impact_model_to_pdf(impact_model)
        subject = "%s for %s" % (confirm_email.subject,
                                 confirmation.impact_model.base_model.name)
        email = EmailMessage(
            subject=subject,
            body=confirm_body,
            reply_to=[request.user.email],
            from_email='ISIMIP Data Confirmation <%s>' %
            settings.DATA_CONFIRMATION_EMAIL,
            to=[settings.DATA_CONFIRMATION_EMAIL],
            cc=[cc.email for cc in ccs],
        )
        filename = "DataConfirmation_%s_%s_%s.pdf" % (
            impact_model.simulation_round.slug,
            impact_model.base_model.sector.slug,
            slugify(impact_model.base_model.name))
        email.attach(filename, pdf, "application/pdf")
        email.send()
        # update confirmation state
        confirmation.is_confirmed = True
        confirmation.confirmed_by = request.user
        confirmation.confirmed_date = datetime.now()
        confirmation.confirmed_license = license
        confirmation.save()
        messages.success(request, 'The data confirmation email has been sent.')
        return HttpResponseRedirect('/dashboard/')
コード例 #47
0
def smart_home_manager():
    try:
        controller_data = requests.get(url, headers=headers).json()
        if controller_data['status'] != 'ok':
            return HttpResponse('Some problems with API', status=502)
    except:
        return HttpResponse('Some problems with API', status=502)

    json_data = {x['name']: x['value'] for x in controller_data.get('data')}
    controllers = json.loads(json.dumps(json_data),
                             object_hook=lambda d: SimpleNamespace(**d))

    payload = {'controllers': []}

    # Если есть протечка воды (leak_detector=true), закрыть холодную (cold_water=false)
    # и горячую (hot_water=false) воду и отослать письмо в момент обнаружения.
    if controllers.leak_detector:
        if controllers.cold_water:
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'cold_water',
                'value': False
            })
            controllers.cold_water = False
        if controllers.hot_water:
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'hot_water',
                'value': False
            })
            controllers.hot_water = False

        email = EmailMessage(
            'leak detector',
            'text',
            settings.EMAIL_HOST,
            [settings.EMAIL_RECEPIENT],
        )
        email.send(fail_silently=False)

    # Если холодная вода (cold_water) закрыта, немедленно выключить бойлер (boiler) и стиральную машину (washing_machine)
    # и ни при каких условиях не включать их, пока холодная вода не будет снова открыта.
    if not controllers.cold_water:
        if controllers.boiler:
            controllers.boiler = False
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'boiler',
                'value': False
            })
        if controllers.washing_machine in ('on', 'broken'):
            controllers.washing_machine = 'off'
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'washing_machine',
                'value': 'off'
            })

    # Если обнаружен дым (smoke_detector), немедленно выключить следующие приборы
    # [air_conditioner, bedroom_light, bathroom_light, boiler, washing_machine],
    # и ни при каких условиях не включать их, пока дым не исчезнет
    if controllers.smoke_detector:
        if controllers.air_conditioner:
            controllers.air_conditioner = False
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'air_conditioner',
                'value': False
            })
        if controllers.bedroom_light:
            controllers.bedroom_light = False
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'bedroom_light',
                'value': False
            })
        if controllers.bathroom_light:
            controllers.bathroom_light = False
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'bathroom_light',
                'value': False
            })
        if controllers.boiler:
            controllers.boiler = False
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'boiler',
                'value': False
            })
        if controllers.washing_machine in ('on', 'broken'):
            controllers.washing_machine = 'off'
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'washing_machine',
                'value': 'off'
            })

    # Если горячая вода имеет температуру (boiler_temperature) меньше чем hot_water_target_temperature - 10%, нужно включить бойлер (boiler),
    # и ждать пока она не достигнет температуры hot_water_target_temperature + 10%, после чего в целях экономии энергии бойлер нужно отключить
    hot_water_target_temperature = Setting.objects.get(
        controller_name='hot_water_target_temperature').value
    if (
            controllers.boiler_temperature or 0
    ) < hot_water_target_temperature * 0.9 and not controllers.boiler and not controllers.smoke_detector and controllers.cold_water:
        controllers.boiler = True
        payload['controllers'] = append_if_not_in(payload['controllers'], {
            'name': 'boiler',
            'value': True
        })

    if (controllers.boiler_temperature
            or 0) > hot_water_target_temperature * 1.1 and controllers.boiler:
        controllers.boiler = False
        payload['controllers'] = append_if_not_in(payload['controllers'], {
            'name': 'boiler',
            'value': False
        })

    # Если шторы частично открыты (curtains == “slightly_open”), то они находятся на ручном управлении
    # - это значит их состояние нельзя изменять автоматически ни при каких условиях
    # Если на улице (outdoor_light) темнее 50, открыть шторы (curtains), но только если не горит лампа в спальне (bedroom_light).
    # Если на улице (outdoor_light) светлее 50, или горит свет в спальне (bedroom_light), закрыть шторы. Кроме случаев когда они на ручном управлении
    if controllers.curtains != "slightly_open":
        if controllers.outdoor_light < 50 and not controllers.bedroom_light and controllers.curtains == 'close':
            controllers.curtains = 'open'
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'curtains',
                'value': 'open'
            })

        if (controllers.outdoor_light > 50 or
                controllers.bedroom_light) and controllers.curtains == 'open':
            controllers.curtains = 'close'
            payload['controllers'] = append_if_not_in(payload['controllers'], {
                'name': 'curtains',
                'value': 'close'
            })

    # Если температура в спальне (bedroom_temperature) поднялась выше bedroom_target_temperature + 10% - включить кондиционер (air_conditioner),
    # и ждать пока температура не опустится ниже bedroom_target_temperature - 10%, после чего кондиционер отключить
    bedroom_target_temperature = Setting.objects.get(
        controller_name='bedroom_target_temperature').value
    if controllers.bedroom_temperature < bedroom_target_temperature * 0.9 and controllers.air_conditioner:
        controllers.boiair_conditionerler = False
        payload['controllers'] = append_if_not_in(payload['controllers'], {
            'name': 'air_conditioner',
            'value': False
        })

    if controllers.bedroom_temperature > bedroom_target_temperature * 1.1 and not controllers.air_conditioner and not controllers.smoke_detector:
        controllers.air_conditioner = True
        payload['controllers'] = append_if_not_in(payload['controllers'], {
            'name': 'air_conditioner',
            'value': True
        })

    if payload['controllers']:
        try:
            r = requests.post(url, headers=headers, json=payload)
            if r.json()['status'] != 'ok':
                return HttpResponse('Some problems with API', status=502)
        except:
            return HttpResponse('Some problems with API', status=502)
コード例 #48
0
    for cl in oc.event.referral.client.all():
        if cl.person.notify.filter(org_id=org.id) and cl.person.notify.get(
                org_id=org.id
        ).client_event:  # client set to receive a email to remember the event
            for x in cl.person.emails.all():
                to.append(u'%s' % x.email)

    # send email if not empty list
    if to:
        # render html email
        title = u"Lembrete do atendimento"
        text = Context({'oc': oc, 'title': title, 'org': org})
        template = get_template(
            "schedule/schedule_notify_client_event.html").render(text)
        # sendmail
        msg = EmailMessage()
        msg.content_subtype = 'html'
        msg.encoding = "utf-8"
        msg.subject = u"Lembrete do atendimento com %s." % oc.event.referral.professional.all(
        )[0].person.name
        msg.body = template
        msg.to = to

        try:
            msg.send()
            print '--- sendmail %s ' % oc
        except:
            print '--- sendmail error %s ' % datetime.today()

        c += 1  # if just sendmail
コード例 #49
0
 def mail_admin(self, request, selected):
     EmailMessage('Greetings from a ModelAdmin action',
                  'This is the test email from an admin action',
                  '*****@*****.**', ['*****@*****.**']).send()
コード例 #50
0
def send_html_email(to_list, subject, template_name, context, sender='*****@*****.**'):
    msg_html = render_to_string(template_name, context)
    msg = EmailMessage(subject=subject, body=msg_html, from_email=sender, bcc=to_list)
    msg.content_subtype = "html"  # Main content is now text/html
    msg.attach_file('notes/aws-udemy.pdf')
    return msg.send()
コード例 #51
0
ファイル: api.py プロジェクト: rohit04445/project-iotdata
def send(msg):
    subject = 'ALERT MOISTURE-CONTENT'
    message = render_to_string('email.html',{'content':msg})
    email=EmailMessage(subject,message,from_email='*****@*****.**',to=['*****@*****.**','*****@*****.**'])
    email.content_subtype = "html"
    email.send()
コード例 #52
0
def external_mail(modeladmin, request, selected):
    EmailMessage('Greetings from a function action',
                 'This is the test email from a function action',
                 '*****@*****.**', ['*****@*****.**']).send()
コード例 #53
0
def get_product(request, path, out={}):
    slug = path.split('/')[-2]
    if len(path.split('/')) > 2:
        category_slug = path.split('/')[-3]
    if category_slug:
        product = get_object_or_404(Product,
                                    slug=slug,
                                    category__slug=category_slug)
    else:
        product = get_object_or_404(Product, slug=slug)
    tab = request.GET.get('tab', 'description')
    template_name = 'product.html'
    if tab == 'description':
        template_name = 'product.html'
    elif tab == 'docs':
        template_name = 'product_docs.html'
    elif tab == 'photo':
        galleries = product.category.galleries.filter(published=True).all()
        if product.category.parent_id:
            galleries = chain(
                galleries,
                product.category.parent_id.galleries.filter(
                    published=True).all())
        galleries = set(galleries)
        out.update({'galleries': galleries})
        template_name = 'product_photo.html'
    elif tab == 'articles':
        template_name = 'product_articles.html'
        articles = set(product.category.articles.all()) | set(
            product.articles.all())
        product.ind_articles = enumerate(articles)
    elif tab == 'review':
        template_name = 'product_review.html'
    out.update({'product': product})
    out.update({'menu_active_item': 'catalog'})
    if request.method == 'POST':
        callback_form = CallbackForm(request.POST, request.FILES)
        if callback_form.is_valid():
            kwargs = dict(
                to=EMAILS_FOR_CALLBACK,
                from_email='*****@*****.**',
                subject=u'Заказ продукции',
                body=
                u'Поступил запрос на заказ продукции {} в количестве {} штук от {} (телефон для связи - {}, email - {}) с комментарием:\n\n"{}"'
                .format(
                    callback_form.cleaned_data['product'],
                    callback_form.cleaned_data['count'],
                    callback_form.cleaned_data['name'],
                    callback_form.cleaned_data['phone'],
                    callback_form.cleaned_data['email'],
                    callback_form.cleaned_data['comment'],
                ),
            )
            message = EmailMessage(**kwargs)
            for attachment in request.FILES.getlist('file_field'):
                message.attach(attachment.name, attachment.read(),
                               attachment.content_type)
            message.send()
            logger.info(u'Send callback with text: {}'.format(kwargs['body']))
    callback_form = CallbackForm()
    out.update({'callback_form': callback_form})
    out.update({'title': product.name})
    return render(request, template_name, out)
コード例 #54
0
 def save_model(self, request, obj, form, change=True):
     EmailMessage('Greetings from a created object',
                  'I hereby inform you that some user created me',
                  '*****@*****.**', ['*****@*****.**']).send()
     return super(ArticleAdmin, self).save_model(request, obj, form, change)
コード例 #55
0
def send_email(to, status):
    msg = EmailMessage("Your Product Status", str(status), to=[
        str(to),
    ])
    msg.send()
コード例 #56
0
def catalog_category(request, category_path):
    out = {}
    category_slug = category_path.split('/')[-2]
    if len(category_path.split('/')) > 2:
        parent_category_slug = category_path.split('/')[-3]
    category = CategoryProduct.objects.filter(slug=category_slug).first()
    out.update({'menu_active_item': 'catalog'})
    out.update({'category_path': category_path})
    if category:
        category.number = Product.objects.filter(published=True,
                                                 category=category).count()
        for child_category in CategoryProduct.objects.filter(
                published=True, parent_id=category.id).all():
            category.number += Product.objects.filter(
                published=True, category=child_category).count()
        if CategoryProduct.objects.filter(parent_id=category.id):
            title = 'Вложенные категории'
            subcategories = CategoryProduct.objects.filter(
                parent_id=category.id, published=True).all()
            for subcategory in subcategories:
                subcategory_products_all = Product.objects.filter(
                    published=True, category=subcategory)
                subcategory.number = subcategory_products_all.count()
                for child_category in CategoryProduct.objects.filter(
                        published=True, parent_id=subcategory.id).all():
                    subcategory_products_all = subcategory_products_all | Product.objects.filter(
                        published=True, category=child_category)
                    subcategory.number += Product.objects.filter(
                        published=True, category=child_category).count()
                subcategory.min_price = None
                for product in subcategory_products_all:
                    current = product.properties.filter(
                        Q(property__title__contains='Цена')).first()
                    try:
                        if current and not subcategory.min_price:
                            subcategory.min_price = float(
                                unicode(current.value).replace(
                                    u' ', u'').replace(u'\xa0', u''))
                        if current and float(
                                current.value.replace(' ', '').replace(
                                    u'\xa0', '')) < subcategory.min_price:
                            subcategory.min_price = float(
                                current.value.replace(' ',
                                                      '').replace(u'\xa0', ''))
                    except Exception:
                        pass
            template_name = 'catalog_category.html'
            ind_subcategory = enumerate(subcategories)
            if request.GET.get('expand', 'true') == 'true':
                template_name = 'catalog_category_expand.html'
            out.update({
                'subcategories': subcategories,
                'title': title,
                'category': category,
                'request': request,
                'ind_subcategory': ind_subcategory
            })
            out.update({'title': category.name})
            return render(request, template_name, out)
        else:
            title = 'Список продуктов'
            products = Product.objects.filter(category=category,
                                              published=True)
            for product in products.all():
                product.properties_dict = product.properties.values(
                    'property__title', 'value')
            template_name = 'catalog_category_products.html'
            ind_products = enumerate(products.all())
            properties = []
            properties_ids = ProductProperty.objects.filter(
                product__in=products).values_list('property',
                                                  flat=True).distinct().all()
            for property_id in properties_ids:
                properties.append(Property.objects.get(pk=property_id))
            properties.sort()
            # найти минимальное и максимальное значение в каждом свойстве
            for property in properties:
                all_value = list(
                    ProductProperty.objects.filter(
                        product__in=products,
                        property=property).values_list('value', flat=True))
                all_value_int = []
                for value in all_value:
                    try:
                        all_value_int.append(
                            float(
                                value.replace(',', '.').replace(
                                    ' ', '').replace(u'\xa0', '').replace(
                                        u'\u2014', '').replace('-', '')))
                    except Exception:
                        all_value_int = [0]
                property.min = unicode(min(all_value_int)).replace(',', '.')
                property.max = unicode(max(all_value_int)).replace(',', '.')
                property.get_min = property.min
                property.get_max = property.max
            # фильтрация по гет-параметрам
            for property in properties:
                property_get_param_from = property.slug + '_from'
                property_value_from = request.GET.get(property_get_param_from,
                                                      None)
                if property_value_from:
                    property.get_min = property_value_from
                    for product in products:
                        if not float(
                                product.properties.filter(
                                    property=property).first().value.replace(
                                        ',',
                                        '.')) >= float(property_value_from):
                            products = products.exclude(pk=product.pk)
                property_get_param_to = property.slug + '_to'
                property_value_to = request.GET.get(property_get_param_to,
                                                    None)
                if property_value_to:
                    property.get_max = property_value_to
                    for product in products:
                        if not float(
                                product.properties.filter(
                                    property=property).first().value.replace(
                                        ',', '.')) <= float(property_value_to):
                            products = products.exclude(pk=product.pk)
            # отфильтровали
            products = products.all()
            for product in products:
                product.properties_dict = {}
                for property in properties:
                    prop = ProductProperty.objects.filter(
                        product=product, property=property).first()
                    if prop:
                        product.properties_dict.update({
                            property.title + ', ' + property.units:
                            prop.value
                        })
                    else:
                        product.properties_dict.update(
                            {property.title + ', ' + property.units: ' - '})
                product.properties_dict = collections.OrderedDict(
                    sorted(product.properties_dict.items()))
            new_properties = []
            for property in properties:
                new_properties.append(u'{}, {}'.format(property.title,
                                                       property.units))
            new_properties.sort()
            if request.GET.get('expand', 'true') == 'true':
                template_name = 'catalog_category_products_expand.html'
            out.update({
                'products': products,
                'parent': category,
                'title': title,
                'category': category,
                'request': request,
                'ind_products': ind_products,
                'properties': new_properties,
                'properties_objs': properties
            })
            if request.method == 'POST':
                callback_form = CallbackForm(request.POST, request.FILES)
                if callback_form.is_valid():
                    kwargs = dict(
                        to=EMAILS_FOR_CALLBACK,
                        from_email='*****@*****.**',
                        subject=u'Заказ продукции',
                        body=
                        u'Поступил запрос на заказ продукции {} в количестве {} штук от {} (телефон для связи - {}, email - {}) с комментарием:\n\n"{}"'
                        .format(
                            callback_form.cleaned_data['product'],
                            callback_form.cleaned_data['count'],
                            callback_form.cleaned_data['name'],
                            callback_form.cleaned_data['phone'],
                            callback_form.cleaned_data['email'],
                            callback_form.cleaned_data['comment'],
                        ),
                    )
                    message = EmailMessage(**kwargs)
                    for attachment in request.FILES.getlist('file_field'):
                        message.attach(attachment.name, attachment.read(),
                                       attachment.content_type)
                    message.send()
                    logger.info(u'Send callback with text: {}'.format(
                        kwargs['body']))
            callback_form = CallbackForm()
            out.update({'callback_form': callback_form})
            out.update({'title': category.name})
            return render(request, template_name, out)
    else:
        return get_product(request, category_path, out)
コード例 #57
0
ファイル: views.py プロジェクト: SketchFrame/sframe
def handlerequest(request):
    form = request.POST
    # x = 'Error Code 10'
    respons_dict = {}
    context = {"title": "handlerequest", "response": respons_dict}
    for i in form.keys():
        respons_dict[i] = form[i]
        if i == 'CHECKSUMHASH':
            checksum = form[i]
            # = 'Error Code 2'
    verify = Checksum.verify_checksum(respons_dict, MERCHANT_KEY, checksum)
    # print(respons_dict)
    if verify:
        if respons_dict['RESPCODE'] == '01':
            # x = 'Error Code 3'
            # print("Order successful")
            ourVar = form['ORDERID']
            find1 = ourVar.find('SFRAME')
            find2 = ourVar[find1+len('SFRAME'):]
            # findMatch = matches.objects.filter(pk = int(find2)).first()
            findOrder = Order.objects.filter(pk=int(find2)).first()
            order_items = findOrder.item.all()

            order_items.update(ordered=True)
            order_items.update(createdOn=timezone.now())
            for item in order_items:
                thisItem = Item.objects.get(pk=item.item.pk)
                thisItem.stock -= item.quantity
                thisItem.save()
                item.save()

            findOrder.ordered = True
            findOrder.amount = form['TXNAMOUNT']
            findOrder.billing_date = timezone.now()
            findOrder.billing_mode = "Online"
            findOrder.save()

            # Checking Affiliate.
            l = []
            for item in findOrder.item.all():
                thisItemSeller = item.item.seller
                affiliate = Affiliate.objects.filter(
                    seller=thisItemSeller.user)
                if len(affiliate) > 0:
                    if affiliate[0].completed == False:
                        affiliate[0].orderItem.add(item)
                        l.append(thisItemSeller.user.user.username)
                        if item.item.discount_price:
                            itemPrice = item.item.discount_price
                        else:
                            itemPrice = item.item.price
                        qty = item.quantity
                        price = (itemPrice/10)*qty
                        affiliate[0].amount += price
                        affiliate[0].save()
                    else:
                        pass
                else:
                    pass
            for user in l:
                affiliate = Affiliate.objects.get(
                    seller__user__username=user)
                affiliate.completed = True
                affiliate.save()

            findAddress = BillingAddress.objects.filter(orderId=find2).first()
            fullname = findAddress.fullname
            user = findAddress.user
            phone = findAddress.phone
            email = findAddress.email
            pincode = findAddress.pincode
            street_address = findAddress.street_address
            street_address2 = findAddress.street_address2
            landmark = findAddress.landmark
            state = findAddress.state
            city = findAddress.city
            amount = form['TXNAMOUNT']

            Pdf(request, find2)

            context.update({'fullname': fullname, 'amount': amount, 'user': user, 'phone': phone, 'pincode': pincode, 'street_address': street_address,
                            'street_address2': street_address2, 'landmark': landmark, 'state': state, 'city': city, 'email': email})
            
            emails = [settings.EMAIL_HOST_USER, ]
            order = Order.objects.get(pk=find2)
            allItems = order.item.all()
            for item in allItems:
                emails.append(item.item.seller.user.user.email)
                Notifications.objects.create(
                    user=item.item.seller.user,
                    title='Someone ordered your product.',
                    category='OrderSuccess'
                )

            msg = EmailMessage('Order Successful at SketchFrame.com',
                               '<html><b><center><h2>An Order has been placed at SketchFrame.com</h2><p>Please visit your dashboard.</p><br/>https://sketchframe.herokuapp.com/seller/dashboard/<br/>or<br/>http://sketchframe.in/seller/dashboard/</center></b></html>', settings.EMAIL_HOST_USER, emails)
            msg.content_subtype = "html"
            # msg.send()
        else:
            print("Order was not successful because " +
                  respons_dict['RESPMSG'])

            ourVar = form['ORDERID']
            find1 = ourVar.find('SFRAME')
            find2 = ourVar[find1+len('SFRAME'):]
            findOrder = Order.objects.filter(pk=int(find2)).first()
            findOrder.delete()
    else:
        print("order unsuccessful because"+respons_dict['RESPMSG'])
    return render(request, 'shop/paymentstatus.html', context)
コード例 #58
0
ファイル: models.py プロジェクト: sudipandatta/nitdgp_website
 def run(self):
     msg = EmailMessage(self.subject, self.html_content, self.sender,
                        self.recipient_list)
     msg.content_subtype = 'html'
     msg.send(fail_silently=False)
コード例 #59
0
ファイル: views.py プロジェクト: SketchFrame/sframe
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        order = Order.objects.get(user=self.request.user, ordered=False)
        amount = order.get_total()
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():
                orderId = order
                fullname = form.cleaned_data.get('fullname')
                email = self.request.user.email
                address_id = self.request.POST.get('address-value')
                address = Address.objects.get(Q(pk=int(address_id)) & Q(user__user=self.request.user))
                payment_type = self.request.POST.get('payment-type')

                billing_address = BillingAddress(
                    user=self.request.user,
                    fullname=fullname,
                    phone=address.phone1,
                    email=email,
                    orderId=orderId,
                    pincode=address.zipCode,
                    street_address=address.address1,
                    street_address2=address.address2,
                    landmark=address.landmark,
                    state=address.state,
                    city=address.city,
                    paymentType=payment_type
                )
                billing_address.save()
                order.billing_address = billing_address
                order.save()

            
                if self.request.POST.get('payment-type') == 'online':
                    # Redirect to payment gateway
                    param_dict = {
                        'MID': 'WorldP64425807474247',
                        'ORDER_ID': str("SFRAME" + str(orderId.pk)),
                        'TXN_AMOUNT': str(amount),
                        'CUST_ID': address.phone1,
                        'INDUSTRY_TYPE_ID': 'Retail',
                        'WEBSITE': 'WEBSTAGING',
                        'CHANNEL_ID': 'WEB',
                        'CALLBACK_URL':'http://127.0.0.1:8000/shop/handlerequest/',
                        # 'CALLBACK_URL': 'https://sketchframe.herokuapp.com/shop/handlerequest/',
                    }
                    param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(
                        param_dict, MERCHANT_KEY)
                    return render(self.request, 'shop/paytm.html', {'param_dict': param_dict})
                elif self.request.POST.get('payment-type') == 'offline':
                    
                    order.amount = amount + 50
                    order.billing_date = timezone.now()
                    order.ordered = True
                    order.billing_mode = "Offline"

                    allItems = order.item.all()

                    allItems.update(ordered=True)
                    allItems.update(createdOn=timezone.now())

                    for item in allItems:
                        thisItem = Item.objects.get(pk=item.item.pk)
                        thisItem.stock -= item.quantity
                        thisItem.save()
                        item.save()
                    order.save()
                    
                    # Checking Affiliate.
                    l = []
                    for item in order.item.all():
                        thisItemSeller = item.item.seller
                        affiliate = Affiliate.objects.filter(seller=thisItemSeller.user)
                        if len(affiliate)>0:
                            if affiliate[0].completed == False:
                                affiliate[0].orderItem.add(item)
                                l.append(thisItemSeller.user.user.username)
                                if item.item.discount_price:
                                    itemPrice = item.item.discount_price
                                else:
                                    itemPrice = item.item.price
                                qty = item.quantity
                                price =  (itemPrice/10)*qty
                                affiliate[0].amount += price
                                affiliate[0].save()
                            else:
                                pass
                        else:
                            pass
                    for user in l:
                        affiliate = Affiliate.objects.get(
                            seller__user__username=user)
                        affiliate.completed = True
                        affiliate.save()
                    
                    Pdf(self.request, order.pk)

                    emails = [settings.EMAIL_HOST_USER, ]
                    order = Order.objects.get(pk=order.pk)
                    allItems = order.item.all()
                    for item in allItems:
                        emails.append(item.item.seller.user.user.email)
                        Notifications.objects.create(
                            user=item.item.seller.user,
                            title='Someone ordered your product.',
                            category='OrderSuccess'
                        )

                    msg = EmailMessage('Order Successful at SketchFrame.com',
                                       '<html><b><center><h2>An Order has been placed at SketchFrame.com</h2><p>Please visit your dashboard.</p><br/>https://sketchframe.herokuapp.com/seller/dashboard/<br/>or<br/>http://sketchframe.in/seller/dashboard/</center></b></html>', settings.EMAIL_HOST_USER, emails)
                    msg.content_subtype = "html"
                    # msg.send()

                    return render(self.request, 'shop/paytm-offline.html', {'order': order})
            messages.warning(self.request, "Failed checkout")
            return redirect('checkout')
        except ObjectDoesNotExist:
            messages.error(self.request, "You don't have an active order")
            return redirect("order-summary")
コード例 #60
0
    def post(self, request):
        context = {'data': request.POST, 'has_error': False}

        email = request.POST.get('email')
        username = request.POST.get('username')
        full_name = request.POST.get('name')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        if len(password) < 6:
            messages.add_message(
                request, messages.ERROR,
                'passwords should be atleast 6 characters long')
            context['has_error'] = True
        if password != password2:
            messages.add_message(request, messages.ERROR,
                                 'passwords dont match')
            context['has_error'] = True

        if not validate_email(email):
            messages.add_message(request, messages.ERROR,
                                 'Please provide a valid email')
            context['has_error'] = True

        try:
            if User.objects.get(email=email):
                messages.add_message(request, messages.ERROR, 'Email is taken')
                context['has_error'] = True

        except Exception as identifier:
            pass

        try:
            if User.objects.get(username=username):
                messages.add_message(request, messages.ERROR,
                                     'Username is taken')
                context['has_error'] = True

        except Exception as identifier:
            pass

        if context['has_error']:
            return render(request, 'auth/register.html', context, status=400)

        user = User.objects.create_user(username=username, email=email)
        user.set_password(password)
        user.first_name = full_name
        user.last_name = full_name
        user.is_active = False
        user.save()

        current_site = get_current_site(request)
        email_subject = 'Active your Account'
        message = render_to_string(
            'auth/activate.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': generate_token.make_token(user)
            })

        email_message = EmailMessage(email_subject, message,
                                     settings.EMAIL_HOST_USER, [email])

        EmailThread(email_message).start()
        messages.add_message(request, messages.SUCCESS,
                             'account created succesfully')

        return redirect('login')