Exemplo n.º 1
0
    def save(self, request, **kwargs):

        email = self.cleaned_data["email"]
        token_generator = kwargs.get("token_generator",
                                     default_token_generator)

        for user in self.users:

            temp_key = token_generator.make_token(user)

            # save it to the password reset model
            # password_reset = PasswordReset(user=user, temp_key=temp_key)
            # password_reset.save()

            current_site = get_current_site()

            # send the password reset email
            path = reverse("account_reset_password_from_key",
                           kwargs=dict(uidb36=user_pk_to_url_str(user),
                                       key=temp_key))
            url = build_absolute_uri(
                request, path,
                protocol=app_settings.DEFAULT_HTTP_PROTOCOL)
            context = {"site": current_site,
                       "user": user,
                       "password_reset_url": url}
            if app_settings.AUTHENTICATION_METHOD \
                    != AuthenticationMethod.EMAIL:
                context['username'] = user_username(user)
            send_db_mail('password-reset', email, context)
        return self.cleaned_data["email"]
Exemplo n.º 2
0
def send_by_dbmail(request):
    if request.method == 'POST':
        kwargs = dict()
        for f in allowed_fields:
            if request.POST.get(f):
                kwargs[f] = request.POST.get(f)

        api_key = kwargs.get('api_key')
        if api_key:
            del kwargs['api_key']
            if not cache.get(api_key):
                get_object_or_404(
                    ApiKey, api_key=api_key, is_active=True)
                cache.set(api_key, 1, timeout=None)

            args = []
            if request.POST.get('data'):
                args = [json.loads(request.POST['data'])]

            if kwargs.get('slug') and kwargs.get('recipient'):
                send_db_mail(
                    kwargs.pop('slug'), kwargs.pop('recipient'),
                    *args, **kwargs)
                return HttpResponse('OK')
    raise Http404
Exemplo n.º 3
0
def check_model(sender, instance, created, **kwargs):
    user = User.objects.get(pk=1)
    field_value_time = str(
        datetime.now().date().strftime("%d/%m/%y")) + " " + str(
            datetime.now().time().strftime("%H:%M"))
    obj = ArticleRevision.objects.all()[len(ArticleRevision.objects.all()) - 1]
    field_name = 'title'
    field_value_name = getattr(obj, field_name)
    field_name = 'content'
    field_value_content = getattr(obj, field_name)
    field_name = 'user'
    field_value_user = getattr(obj, field_name)
    count = 0
    articles = ArticleRevision.objects.all()
    for article in articles:
        if field_value_name == getattr(article, 'title'):
            count += 1

    user_mails = User.objects.all()
    if count > 1:
        MailTemplate.objects.create(
            name="The Article was changed",
            subject="The Article was changed in " +
            str(datetime.now().time().strftime("%H:%M")),
            message="The Article '" + str(field_value_name) +
            "' was changed by " + str(field_value_user) + " in " +
            str(field_value_time) + ". Now content of the '" +
            str(field_value_name) + "' is " + str(field_value_content),
            slug="The Article was changed in " +
            str(datetime.now().date().strftime("%d/%m/%y")) + " " +
            str(datetime.now().time().strftime("%H:%M")),
            is_html=False,
        )
        for users in user_mails:
            send_db_mail("TheArticlewaschangedin" +
                         str(datetime.now().date().strftime("%d%m%y")) + "" +
                         str(datetime.now().time().strftime("%H%M")),
                         users.email,
                         use_celery=False)
    else:
        MailTemplate.objects.create(
            name="The Article was created",
            subject="The Article was created in " +
            str(datetime.now().time().strftime("%H:%M")),
            message="The Article '" + str(field_value_name) +
            "' was created by " + str(field_value_user) + " in " +
            str(field_value_time) + ". The content of the '" +
            str(field_value_name) + "' is " + str(field_value_content),
            slug="The Article was created in " +
            str(datetime.now().date().strftime("%d/%m/%y")) + " " +
            str(datetime.now().time().strftime("%H:%M")),
            is_html=False,
        )
        for users in user_mails:
            send_db_mail("TheArticlewascreatedin" +
                         str(datetime.now().date().strftime("%d%m%y")) + "" +
                         str(datetime.now().time().strftime("%H%M")),
                         users.email,
                         use_celery=False)
Exemplo n.º 4
0
    def send_mail(self):
        from dbmail import send_db_mail

        email_list = self.get_email_list()
        if email_list and not self.signal.is_sent(self.pk):
            send_db_mail(
                self.signal.template.slug, email_list, self.site,
                self.kwargs, self.instance, **self.get_interval()
            )
            self.signal.mark_as_sent(self.pk)
Exemplo n.º 5
0
    def send_mail(self):
        from dbmail import send_db_mail

        email_list = self.get_email_list()
        if email_list and not self.signal.is_sent(self.pk):
            send_db_mail(
                self.signal.template.slug, email_list, self.site,
                self.kwargs, self.instance, queue=SIGNALS_MAIL_QUEUE,
                **self.get_interval()
            )
            self.signal.mark_as_sent(self.pk)
Exemplo n.º 6
0
def send_mail(slug, to, context):
    domain = context.get('domain') or getattr(settings, 'DOMAIN', '')
    protocol = context.get('protocol') or getattr(settings, 'PROTOCOL', 'http')
    site_name = context.get('site_name') or getattr(settings, 'SITE_NAME', '')

    common_context = {
        'domain': domain,
        'protocol': protocol,
        'site_name': site_name,
    }
    common_context.update(context)

    send_db_mail(slug, to, common_context, use_celery=False)
Exemplo n.º 7
0
    def send_mail(self):
        from dbmail import send_db_mail

        email_list = self.get_email_list()
        if email_list and not self.signal.is_sent(self.pk):
            for email in email_list.split(","):
                email = email.strip()
                if email:
                    send_db_mail(
                        self.signal.template.slug, email, self.site,
                        self.kwargs, self.instance, queue=SIGNALS_MAIL_QUEUE,
                        **self.get_interval()
                    )
            self.signal.mark_as_sent(self.pk)
Exemplo n.º 8
0
def offer_change_hook(sender, instance, **kwargs):
    """Update Statistics based on vendor's wares count and value."""
    prev_stats = Statistics.objects.current(instance.vendor)
    new_stats = Statistics.objects.create(instance.vendor, save=False)
    if new_stats == prev_stats:
        return
    new_stats.save()
    if prev_stats.tariff != new_stats.tariff:
        send_db_mail(
            'tariff-changed', instance.vendor.user.email, {
                'tariff':
                new_stats.tariff,
                'discounts':
                Discount.objects.filter(vendor=instance.vendor, usages__gt=0)
            })
Exemplo n.º 9
0
 def verify_email(user, verification_code):
     if not settings.SKIP_SENDING_EMAIL:
         try:
             app_name = "Orchid Roots"
             send_db_mail(
                 'verify-mail',
                 user.email,
                 {
                     'app_name': app_name,
                     'fullname': user.fullname,
                     'verification_code': verification_code,
                 },
             )
         except Exception as e:
             print(str(e))
Exemplo n.º 10
0
 def forget_password_email(user, forget_pass_code):
     if not settings.SKIP_SENDING_EMAIL:
         try:
             app_name = "Orchid Roots"
             send_db_mail(
                 'reset-passcode',
                 user.email,
                 {
                     'app_name': app_name,
                     'fullname': user.fullname,
                     'forget_pass_code': forget_pass_code,
                 },
                 user=user,
             )
         except Exception as e:
             print(str(e))
Exemplo n.º 11
0
def send_test_msg(pk, email, user=None, use_celery=True):
    template = MailTemplate.objects.get(pk=pk)
    slug = template.slug
    var_list = re.findall('\{\{\s?(\w+)\s?\}\}', template.message)
    context = {}
    for var in var_list:
        context[var] = '%s' % var.upper().replace('_', '-')
    return send_db_mail(slug, email, user, context, use_celery=use_celery)
Exemplo n.º 12
0
def send_test_msg(pk, email, user=None, use_celery=True):
    template = MailTemplate.objects.get(pk=pk)
    slug = template.slug
    var_list = re.findall('\{\{\s?(\w+)\s?\}\}', template.message)
    context = {}
    for var in var_list:
        context[var] = '%s' % var.upper().replace('_', '-')
    return send_db_mail(slug, email, user, context, use_celery=use_celery)
Exemplo n.º 13
0
 def verify_email(user, verification_url):
     try:
         app_name = 'Laowai Panda'
         request = CrequestMiddleware.get_request()
         base_url = ("{0}://{1}").format(request.scheme , request._get_raw_host())
         send_db_mail(
             'verify-mail',
             user.email,
             {
                 'base_url':base_url,
                 'app_name': app_name,
                 'verification_url': verification_url,
             },
             user = user,
         )
     except:
         pass
Exemplo n.º 14
0
 def send_temp_password_email(user, temp_code):
     try:
         app_name = 'Laowai Panda'
         request = CrequestMiddleware.get_request()
         base_url = ("{0}://{1}").format(request.scheme , request._get_raw_host())
         send_db_mail(
             'reset-passcode',
             user.email,
             {
                 'app_name':app_name,
                 'base_url':base_url,
                 'temp_code': temp_code,
             },
             user = user,
         )
     except:
         pass
Exemplo n.º 15
0
 def send_report_question(reporter_user, question_url):
     try:
         app_name = 'Laowai Panda'
         request = CrequestMiddleware.get_request()
         base_url = ("{0}://{1}").format(request.scheme , request._get_raw_host())
         send_db_mail(
             'laowai_panda-question-report',
             settings.SYS_ADMINS,
             {
                 'app_name':app_name,
                 'base_url':base_url,
                 'email': reporter_user.email,
                 'username': reporter_user.username,
                 'question_url': question_url,
             },
         )
     except:
         pass
Exemplo n.º 16
0
def transition_change_notification(order):
    """
    This function shall be called, after an Order object performed a transition change.

    """
    if not isinstance(order, BaseOrder):
        raise TypeError("Object order must inherit from class BaseOrder")
    emails_in_queue = False
    for notification in Notification.objects.filter(transition_target=order.status):
        recipient = notification.get_recipient(order)
        if recipient is None:
            continue

        # emulate a request object which behaves similar to that one, when the customer submitted its order
        emulated_request = EmulateHttpRequest(order.customer, order.stored_request)
        customer_serializer = app_settings.CUSTOMER_SERIALIZER(order.customer)
        render_context = {'request': emulated_request, 'render_label': 'email'}
        order_serializer = OrderDetailSerializer(order, context=render_context)
        language = order.stored_request.get('language')
        context = {
            'customer': customer_serializer.data,
            'order': order_serializer.data,
            'ABSOLUTE_BASE_URI': emulated_request.build_absolute_uri().rstrip('/'),
            'render_language': language,
        }
        try:
            latest_delivery = order.delivery_set.latest()
            context['latest_delivery'] = DeliverySerializer(latest_delivery, context=render_context).data
        except (AttributeError, models.ObjectDoesNotExist):
            pass
        # try:
        #     template = notification.mail_template.translated_templates.get(language=language)
        # except MailTemplate.DoesNotExist:
        #     template = notification.mail_template
        attachments = {}
        for notiatt in notification.notificationattachment_set.all():
            attachments[notiatt.attachment.original_filename] = notiatt.attachment.file.file
        # mail.send(recipient, template=template, context=context,
        #           attachments=attachments, render_on_delivery=True)
        send_db_mail(notification.mail_template.slug, recipient, context, attachments=attachments, use_celery=False)
        emails_in_queue = True
    if emails_in_queue:
        email_queued()
Exemplo n.º 17
0
def send_by_dbmail(request):
    if request.method == 'POST':
        kwargs = dict()
        for f in allowed_fields:
            if request.POST.get(f):
                kwargs[f] = request.POST.get(f)

        api_key = kwargs.get('api_key')
        if api_key:
            del kwargs['api_key']
            if not cache.get(api_key):
                get_object_or_404(ApiKey, api_key=api_key, is_active=True)
                cache.set(api_key, 1, timeout=defaults.CACHE_TTL)

            args = []
            if request.POST.get('data'):
                args = [json.loads(request.POST['data'])]

            if kwargs.get('slug') and kwargs.get('recipient'):
                send_db_mail(kwargs.pop('slug'), kwargs.pop('recipient'),
                             *args, **kwargs)
                return HttpResponse('OK')
    raise Http404
Exemplo n.º 18
0
    def send_mail_with_db_mail(self, request, **kwargs):
        current_site = kwargs["site"] if "site" in kwargs \
            else Site.objects.get_current()
        activate_url = reverse("account_confirm_email", args=[self.key])
        if request is not None:
            activate_url = build_absolute_uri(request,
                                              activate_url,
                                              protocol=app_settings.DEFAULT_HTTP_PROTOCOL)
        else:
            activate_url = 'http://%s%s' % (current_site.domain, activate_url)

        ctx = {
            "user": self.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            'expiration_days': app_settings.EMAIL_CONFIRMATION_EXPIRE_DAYS,
            "key": self.key,
        }
        send_db_mail('email-confirmation', self.email_address.email, ctx)
        self.sent = timezone.now()
        self.save()
        signals.email_confirmation_sent.send(sender=self.__class__,
                                             confirmation=self)
Exemplo n.º 19
0
def send_mail():

	send_db_mail(
	    # slug - which defined on db template
	    'welcome-template',

	    # recipient can be list, or str separated with comma or simple string
	    # '*****@*****.**' or '[email protected], [email protected]' or
	    # ['*****@*****.**', '*****@*****.**'] or string Mail group slug
	    '*****@*****.**',

	    # All *args params will be accessible on template context
	    {
	        'first_name': 'Rishikesh'
	    },

	    # You can access to all model fields. For m2m and fk fields, you should use module_name
	    # MyModel.objects.get(pk=1),

	    #######################################################################
	    ### Optional kwargs:
	    #######################################################################
	    # from_email='',
	    cc=['*****@*****.**'],
	    bcc=['*****@*****.**'],

	    # # For store on mail logs
	    # user=User.objects.get(pk=1),

	    # # Current language code, which selected by user
	    # language='ru',

	    # # This options is documented on the Django docs
	    # attachments=[(filename, content, mimetype)],
	    # files=['hello.jpg', 'world.png'],
	    # headers={'Custom-Header':'Some value'},

	    # # For working with different queue, you can specify queue name on the settings, or on option
	    # queue='default',

	    # # Time for retry failed send. Working with celery only
	    # retry_delay=300,

	    # # Max retries, when sending is failed
	    # max_retries=3,

	    # # You can disable retry function
	    # retry=True,

	    # # Hard limit on seconds
	    # time_limit=30,

	    # # Postpone send email for specified seconds
	    # send_after=60,

	    # # You can disable celery for debug messages, or when error is occurred,
	    # # and email can not be delivered by celery.
	    # # Or some part of your app run on instance, where celery is not used.
	    # use_celery=True,

	    # # ...
	    # # another named arguments, which supported by specified backend
	    # # ...
	)
Exemplo n.º 20
0
def make_sended(modeladmin, request, queryset):
    obj = MTemplate.objects.all()[len(MTemplate.objects.all())-1]
    field = 'slug'
    slug = getattr(obj, field)
    send_db_mail(str(slug), '*****@*****.**',  use_celery=False)
    queryset.update(status='s', draft=True)
Exemplo n.º 21
0
def vendor_closed_hook(sender, instance, **kwargs):
    """Finalize Billing and Statistics for a closed vendor."""
    Billing.objects.get(vendor=instance).close()
    Statistics.objects.create(vendor=instance)
    send_db_mail('tariff-closed', instance.user.email, {"vendor": instance})
Exemplo n.º 22
0
    def post(self, request, *args, **kwargs):
        """Create a user account in case of anonymous user."""
        if "abort" in request.POST:
            # we haven't created order so just quit
            return redirect("cart")

        addresses_form = core_forms.AddressesForm(
            data=request.POST,
            billing=core_utils.get_billing_address_from_request(self.request),
            shipping=core_utils.get_shipping_address_from_request(
                self.request),
            billing_form_class=self.get_billing_form_class(),
            shipping_form_class=self.get_shipping_form_class(),
        )
        kwargs['addresses_form'] = addresses_form

        if request.user.is_anonymous():
            # create a user account for anonymous and log him in
            adapter = account.adapter.get_adapter(request)
            # first verify email and included captcha form
            email_form = core_forms.SecuredEmailForm(request.POST,
                                                     request=request)
            kwargs['email_form'] = email_form
            if not (email_form.is_valid() and addresses_form.is_valid()):
                return self.get(request, *args, **kwargs)

            # if EmailForm showed password and it was correct it would return user
            user = email_form.cleaned_data.get("user")
            if user is None:
                email = email_form.cleaned_data['email']
                # if email and captcha is alright then register the user
                # addresses_form.full_clean()
                name = addresses_form.cleaned_data['shipping'].get('name') or \
                       addresses_form.cleaned_data['billing'].get('name')

                user, created = core_models.User.objects.get_or_create(
                    name=name, email=email)
                mail_context = {'user': user}

                if created:
                    email_address = account.models.EmailAddress.objects.add_email(
                        request, user, email, confirm=False, signup=False)
                    email_address.set_as_primary()

                # email saying that we have saved user's login informations
                # with one-time login link 'admin-email-login'
                dbmail.send_db_mail("core-email-login",
                                    email,
                                    mail_context,
                                    user=user)

                # Do not send email confirmation - confirm the email
                # once the order itself is confirmed by email link
                # account.models.EmailConfirmation.create(email_address)

            # login new user without requesting their password
            adapter.login(request, user)

        # assigns Cart to new User in case user accound didn't exist before
        cart = utils.get_or_create_cart(self.request)
        if cart.user != request.user:
            cart.user = request.user
            cart.save()
        # check whether all products in the cart are not sold out.
        remove = []
        for cartitem in cart.items.all():
            if cartitem.item.quantity >= 0 and cartitem.quantity > cartitem.item.quantity:
                remove.append(cartitem)
                messages.warning(
                    request,
                    str(cartitem.item) + " " + str(_("has been sold out.")))
            if not cartitem.item.active:
                remove.append(cartitem)
                messages.warning(
                    request,
                    str(cartitem.item) + " " +
                    str(_("has been removed by vendor.")))
        for cartitem in remove:
            cartitem.delete()

        # save precious adresses into database and request
        extra_info_form = model_forms.modelform_factory(models.OrderExtraInfo,
                                                        exclude=['order'])(
                                                            request.POST)
        kwargs['extra_info_form'] = extra_info_form

        if not all((addresses_form.is_valid(), extra_info_form.is_valid())):
            return self.get(self, *args, **kwargs)

        # Add the address to the request
        billing_address, shipping_address = \
            addresses_form.save_to_request(self.request)

        # Here it is! Turn Cart into Order!
        order = models.Order.objects.create_from_cart(cart, self.request)
        utils.add_order_to_request(self.request, order)

        # Save addresses into the order
        order.set_shipping_address(shipping_address)
        order.set_billing_address(billing_address)
        order.save()

        return redirect("checkout-shipping")
Exemplo n.º 23
0
def send_mail(slug, recipient, context=None, *args, **kwargs):
    context = context or {}
    context.update(get_context())
    send_db_mail(slug, recipient, context, *args, **kwargs)
Exemplo n.º 24
0
 def send(self):
     """Send an email with proforma/invoice."""
     send_db_mail("tariff-billed",
                  self.vendor.user.email, {'bill': self},
                  attachments=[self.export_attachment()])