Exemple #1
0
def question_and_answer_page_processor(request, page):
    if request.method == 'POST':
        url = page.get_absolute_url() + "?sent=1"

        question_form = AskedQuestionForm(data=request.POST)
        question = question_form.save(page.qapage, request.user)

        fields = [('questioner', question.questioner),
                  ('question', question.question)]

        responder_mail = split_addresses(page.qapage.responder_mail)
        if responder_mail:
            send_mail_template(page.title,
                               'email/form_response',
                               None,
                               responder_mail,
                               context={
                                   'message':
                                   _('A new question is waiting for you!'),
                                   'fields':
                                   fields
                               })

        return redirect(url)

    question_form = AskedQuestionForm()
    return {'form': question_form}
Exemple #2
0
def send_verification_mail_for_email_update(request, user, new_email, verification_type):
    """
    Sends an email with a verification link to users when
    they update their email. The email is sent to the new email.
    The actual update of the email happens only after
    the verification link is clicked.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = reverse(verification_type, kwargs={
        "uidb36": int_to_base36(user.id),
        "token": default_token_generator.make_token(user),
        "new_email": new_email
    }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "new_email": new_email,
        "verify_url": verify_url,
    }
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject, "email/%s" % verification_type,
                       settings.DEFAULT_FROM_EMAIL, new_email,
                       context=context)
Exemple #3
0
def request_group(request):
    try:
        form = ActionGroupRequestForm(request.POST or None)
        if request.method == 'POST' and form.is_valid():
            form.save()
            actiongroup = form.instance
            send_mail_template('Action Group Application Submitted: %s' %
                               actiongroup.title,
                               'sfpirg/email/ag_application',
                               Settings.get_setting('SERVER_EMAIL'),
                               actiongroup.contact_email,
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
            send_mail_template(
                'Action Group Application Submitted: %s' % actiongroup.title,
                'sfpirg/email/ag_admin_application',
                Settings.get_setting('SERVER_EMAIL'),
                Settings.get_setting('ACTION_GROUPS_ADMIN_EMAIL'),
                context=locals(),
                attachments=None,
                fail_silently=settings.DEBUG,
                addr_bcc=None)
            return HttpResponseRedirect(resolve_url('thankyou'))
        current_item = 'Action Group Request'
        context = RequestContext(request, locals())
        return render_to_response('sfpirg/action_group_request.html', {},
                                  context_instance=context)
    except:
        log.error('Failed to process request', exc_info=1)
Exemple #4
0
def organization(request):
    user = request.user
    org = get_org(request)
    form = OrganizationForm(request.POST or None,
                            instance=org,
                            initial={
                                'contact_name': user.get_full_name(),
                                'contact_email': user.email
                            })
    if request.method == 'POST' and form.is_valid():
        form.save()
        user.profile.organization = form.instance
        user.profile.save()
        if not org:
            # This is a new organization!
            send_mail_template('Action Group Application Submitted: %s' %
                               form.instance.title,
                               'sfpirg/email/arx_new_organization',
                               Settings.get_setting('SERVER_EMAIL'),
                               request.user.email,
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
        return HttpResponseRedirect(request.GET.get('next', '/'))
    context = RequestContext(request, locals())
    return render_to_response('sfpirg/organization.html', {},
                              context_instance=context)
Exemple #5
0
    def send_email_to_requester(self, request):
        template = "openhelpdesk/email/report/info_to_request"
        operator = request.user
        operator_name = operator.username
        if operator.last_name and operator.first_name:
            operator_name = '{} {}'.format(operator.first_name,
                                           operator.last_name)
        context = {'report_name': self._meta.verbose_name.lower(),
                   'operator': operator,
                   'operator_name': operator_name,
                   'ticket_id': self.ticket_id,
                   'email_background_color': (
                       OrganizationSetting.email_objects.get_color(
                           self.ticket.requester.email))}

        try:
            site_conf = SiteConfiguration.objects.get(site=self.ticket.site)
            addr_from = site_conf.email_addr_from
        except (SiteConfiguration.DoesNotExist, Ticket.DoesNotExist):
            addr_from = SiteConfiguration.get_no_site_email_addr_from()

        subject = subject_template("{}_subject.html".format(template), context)
        addr_to = [self.ticket.requester.email]
        change_ticket_url = '{}#tab_messages'.format(
            reverse(admin_urlname(self.ticket._meta, 'change'),
                    args=(self.ticket_id,)))
        context.update({'report': self, 'request': request,
                        'change_ticket_url': change_ticket_url})
        send_mail_template(subject, template, addr_from, addr_to,
                           context=context, attachments=None)
Exemple #6
0
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()
    order_context = {
        "order": order,
        "request": request,
        "order_items": order.items.all()
    }
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/order_receipt.html")
    except TemplateDoesNotExist:
        receipt_template = "email/order_receipt"
    else:
        receipt_template = "shop/email/order_receipt"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_ORDER_EMAIL_SUBJECT,
                       receipt_template,
                       settings.SHOP_ORDER_FROM_EMAIL,
                       order.billing_detail_email,
                       context=order_context,
                       addr_bcc=settings.SHOP_ORDER_EMAIL_BCC or None)
Exemple #7
0
 def send_email_to_operators_on_adding(self, request):
     template = "openhelpdesk/email/ticket/ticket_operators_creation"
     subject = subject_template(
         "{}_subject.html".format(template), {
             'ticket_name': self._meta.verbose_name.lower(),
             'username': self.requester.username
         })
     try:
         site_conf = SiteConfiguration.objects.get(site=self.site)
         addr_from = site_conf.email_addr_from
         addr_to = site_conf.email_addrs_to
     except SiteConfiguration.DoesNotExist:
         addr_from = SiteConfiguration.get_no_site_email_addr_from()
         addr_to = SiteConfiguration.get_no_site_email_addrs_to()
     change_url = reverse(admin_urlname(self._meta, 'change'),
                          args=(self.pk, ))
     context = {
         'ticket_name': self._meta.verbose_name,
         'ticket': self,
         'request': request,
         'change_url': change_url
     }
     send_mail_template(subject,
                        template,
                        addr_from,
                        addr_to,
                        context=context,
                        attachments=None)
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        if request.user.is_authenticated():
            comment.user = request.user
            comment.user_name = best_name(comment.user)

        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")
        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        notify_emails.append(obj.user.email)
        reply_to_comment = comment.replied_to
        if reply_to_comment is not None:
            notify_emails.append(reply_to_comment.user.email)
        if notify_emails:
            subject = "[HydroShare Support] New comment by {c_name} for: {res_obj}".format(
                c_name=comment.user_name, res_obj=str(obj))
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context)

        return comment
Exemple #9
0
def about_pg(request, page):
    form = ContactForm()
    if request.method == "POST":
        form = ContactForm(request.POST or None)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            name = form.cleaned_data['name']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            # Form processing goes here.
            context = {
                "from_email": from_email,
                "name": name,
                "message": message,
                "subject": subject,
                "request": request
            }
            send_mail_template(
                "About pg contact form submission | {}".format(subject),
                "email/thanks",
                settings.DEFAULT_FROM_EMAIL,
                settings.DEFAULT_RECEIVE_EMAIL,
                context=context)
            # # info(request, _(""))
            return redirect("email_received")
    return {"form": form}
Exemple #10
0
def request_join(request, team_id):
    if registration_period_ended(request):
        messages.error(request, _("registration period has ended"))
        return redirect('teams_list')
    try:
        team = Team.objects.get(id=team_id)
    except Team.DoesNotExist:
        raise Http404()
    if request.user.team:
        messages.error(request, _("you already have a team"))
    if team.member_set.count() == team.competition.max_members:
        messages.error(request, _("the team has reached max members"))
    elif team.final:
        messages.error(request, _("The team is final."))
    else:
        req, is_new = JoinRequest.objects.get_or_create(team=team, member=request.user)
        if is_new:
            send_mail_template(_('AIChallenge team join request'), 'mail/join_request_mail', '', team.head.email,
                               context={'member': request.user.get_full_name()})
            messages.success(request, _('join request has been sent'))
            messages.info(request, _("please check spams too"))
        else:
            if req.accepted is False:
                messages.error(request, _('your request to join this team has been declined'))
            else:
                messages.warning(request, _('you have requested to join this team before'))
    return redirect('teams_list')
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()

    address = request.session['address']

    store = request.session['stores']
    store_name = store[0].name
    store_address = store[0].address
    store_contact = store[0].contact_number

    order_context = {"order": order, "request": request,
                     "order_items": order.items.all(), "address": address,
                     "store_name": store_name, "store_address": store_address,
                     "store_contact": store_contact}
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/order_receipt.html")
    except TemplateDoesNotExist:
        receipt_template = "email/order_receipt"
    else:
        receipt_template = "shop/email/order_receipt"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_ORDER_EMAIL_SUBJECT,
        receipt_template, settings.SHOP_ORDER_FROM_EMAIL,
        order.billing_detail_email, context=order_context,
        fail_silently=settings.DEBUG)
 def save(self, request):
     """
     Saves a new comment and sends any notification emails.
     """
     comment = self.get_comment_object()
     obj = comment.content_object
     if request.user.is_authenticated():
         comment.user = request.user
     comment.by_author = request.user == getattr(obj, "user", None)
     comment.ip_address = ip_for_request(request)
     comment.replied_to_id = self.data.get("replied_to")
     comment.save()
     comment_was_posted.send(sender=comment.__class__,
                             comment=comment,
                             request=request)
     notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
     if notify_emails:
         subject = ugettext("New comment for: ") + str(obj)
         context = {
             "comment": comment,
             "comment_url": add_cache_bypass(comment.get_absolute_url()),
             "request": request,
             "obj": obj,
         }
         send_mail_template(subject, "email/comment_notification",
                            settings.DEFAULT_FROM_EMAIL, notify_emails,
                            context)
     return comment
Exemple #13
0
 def save(self, request):
     """
     Saves a new comment and sends any notification emails.
     """
     comment = self.get_comment_object()
     obj = comment.content_object
     if request.user.is_authenticated():
         comment.user = request.user
     comment.by_author = request.user == getattr(obj, "user", None)
     comment.ip_address = ip_for_request(request)
     comment.replied_to_id = self.data.get("replied_to")
     comment.save()
     comment_was_posted.send(sender=comment.__class__, comment=comment,
                             request=request)
     notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
     if notify_emails:
         subject = _("New comment for: ") + str(obj)
         context = {
             "comment": comment,
             "comment_url": add_cache_bypass(comment.get_absolute_url()),
             "request": request,
             "obj": obj,
         }
         send_mail_template(subject, "email/comment_notification",
                            settings.DEFAULT_FROM_EMAIL, notify_emails,
                            context)
     return comment
Exemple #14
0
def send_verification_mail_for_email_update(request, user, new_email,
                                            verification_type):
    """
    Sends an email with a verification link to users when
    they update their email. The email is sent to the new email.
    The actual update of the email happens only after
    the verification link is clicked.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = reverse(verification_type,
                         kwargs={
                             "uidb36": int_to_base36(user.id),
                             "token": default_token_generator.make_token(user),
                             "new_email": new_email
                         }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "new_email": new_email,
        "verify_url": verify_url,
    }
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/%s" % verification_type,
                       settings.DEFAULT_FROM_EMAIL,
                       new_email,
                       context=context)
Exemple #15
0
def request_join(request, team_id):
    if registration_period_ended(request):
        messages.error(request, _("registration period has ended"))
        return redirect('teams_list')
    try:
        team = Team.objects.get(id=team_id)
    except Team.DoesNotExist:
        raise Http404()
    if request.user.team:
        messages.error(request, _("you already have a team"))
    if team.member_set.count() == team.competition.max_members:
        messages.error(request, _("the team has reached max members"))
    elif team.final:
        messages.error(request, _("The team is final."))
    else:
        req, is_new = JoinRequest.objects.get_or_create(team=team,
                                                        member=request.user)
        if is_new:
            send_mail_template(
                _('AIChallenge team join request'),
                'mail/join_request_mail',
                '',
                team.head.email,
                context={'member': request.user.get_full_name()})
            messages.success(request, _('join request has been sent'))
            messages.info(request, _("please check spams too"))
        else:
            if req.accepted is False:
                messages.error(
                    request,
                    _('your request to join this team has been declined'))
            else:
                messages.warning(
                    request, _('you have requested to join this team before'))
    return redirect('teams_list')
Exemple #16
0
def resend_invitation_mail(request):
    if registration_period_ended(request):
        return HttpResponse(json.dumps({
            "success":
            False,
            "message":
            str(_("registration period has ended"))
        }),
                            content_type='application/json')
    id = request.POST.get('id')
    try:
        invitation = TeamInvitation.objects.get(pk=id)
    except TeamInvitation.DoesNotExist:
        raise Http404()
    is_head = request.team.head == request.user
    if not is_head or request.team.pk != invitation.team.pk:
        raise PermissionDenied()

    send_mail_template(_('AIChallenge team invitation'),
                       'mail/invitation_mail',
                       '',
                       invitation.member.email,
                       context={
                           'team': invitation.team.name,
                           'abs_link': invitation.accept_link,
                           'current_host': request.get_host
                       })
    messages.info(request, _("please check spams too"))
    return HttpResponse(json.dumps({
        "success": True,
        "message": _("invitation resend successful")
    }),
                        content_type='application/json')
def modularpage_processor(request, page):
    formblock_ct = ContentType.objects.get(app_label='clubhouse_forms',\
            model='formblock')

    # TODO: Fix this to find form objects in any of the BlockContexts registered here
    formblocks = page.modularpage.content.filter(block_type=formblock_ct)
    from clubhouse.forms import Initialised

    for formblock in formblocks:
        registry_key = 'form:%s' % formblock.block_object.pk
        form_model = formblock.block_object.form
        form = FormForForm(formblock.block_object.form, RequestContext(request),
                           None, None)

        post_data = request.POST or {}
        if form.submit_key in post_data:
            form = FormForForm(formblock.block_object.form,
                    RequestContext(request), request.POST, request.FILES or None)

        if form.is_valid():
            url = page.get_absolute_url()
            if is_spam(request, form, url):
                return redirect(url)
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            entry = form.save()
            subject = form_model.email_subject
            if not subject:
                subject = "%s - %s" % (form_model.title, entry.entry_time)
            fields = [(v.label, format_value(form.cleaned_data[k]))
                      for (k, v) in form.fields.items()]
            context = {
                "fields": fields,
                "message": form_model.email_message,
                "request": request,
            }
            email_from = form_model.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form.email_to()
            if email_to and form_model.send_email:
                send_mail_template(subject, "email/form_response", email_from,
                                   email_to, context)
            headers = None
            if email_to:
                # Add the email entered as a Reply-To header
                headers = {'Reply-To': email_to}
            email_copies = split_addresses(form_model.email_copies)
            if email_copies:
                send_mail_template(subject, "email/form_response_copies",
                                   email_from, email_copies, context,
                                   attachments=attachments, headers=headers)
            form_valid.send(sender=request, form=form, entry=entry)
            form.is_submitted = True
        else:
            form_invalid.send(sender=request, form=form)

        Initialised.register(registry_key, form)

    return {}
Exemple #18
0
    def send_email_to_requester(self, request):
        template = "openhelpdesk/email/report/info_to_request"
        context = {
            'report_name': self._meta.verbose_name.lower(),
            'operator': request.user.username,
            'ticket_id': self.ticket_id
        }

        subject = subject_template("{}_subject.html".format(template), context)
        addr_from = request.user.email
        addr_to = [self.ticket.requester.email]
        change_ticket_url = '{}#tab_messages'.format(
            reverse(admin_urlname(self.ticket._meta, 'change'),
                    args=(self.ticket_id, )))
        context.update({
            'report': self,
            'request': request,
            'change_ticket_url': change_ticket_url
        })
        send_mail_template(subject,
                           template,
                           addr_from,
                           addr_to,
                           context=context,
                           attachments=None)
Exemple #19
0
def reservation_send(request):
    if not request.is_ajax():
        raise Http404()

    if request.method != 'POST':
        raise Http404()

    f = settings.RESERV_EMAIL_FROM
    t = settings.RESERV_EMAIL_TO
    if f and t:
        C = {'message': "Reservation request raised", 'fields': []}

        for k, v in request.POST.iteritems():
            if k != 'csrfmiddlewaretoken':
                C['fields'].append((
                    k,
                    v,
                ))

        send_mail_template(
            addr_from=f,
            addr_to=[
                t,
            ],
            template='email/form_response',
            subject="WEB RESERVATION REQUEST",
            context=C,
        )

    return HttpResponse("test")
Exemple #20
0
 def handle(self, *args, **ops):
     count = 0
     verification_type = "signup_verify"
     request = {'get_host': 'aichallenge.sharif.edu:2016'}
     for user in tqdm(Member.objects.filter(is_active=False), leave=False):
         verify_url = reverse(
             verification_type,
             kwargs={
                 "uidb36": int_to_base36(user.id),
                 "token": default_token_generator.make_token(user),
             }) + "?next=" + "/"
         context = {
             "request": request,
             "user": user,
             "verify_url": verify_url,
         }
         subject_template_name = "email/%s_subject.txt" % verification_type
         subject = subject_template(subject_template_name, context)
         send_mail_template(subject,
                            "email/%s" % verification_type,
                            settings.DEFAULT_FROM_EMAIL,
                            user.email,
                            context=context)
         count += 1
     self.stdout.write("resent %d verification email" % count)
Exemple #21
0
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(pk=kwargs['pk'])

        if order.status == 1:
            order.status = 2 # set to payed
            order.save()

            order_context = {"order": order, "request": request,
                             "order_items": order.items.all()}
            order_context.update(order.details_as_dict())

            # send email with order to producer
            send_mail_template("Bestellung #%i" % order.id,
                           "email/producer_notification",
                           settings.SHOP_ORDER_FROM_EMAIL,
                           settings.SHOP_PRODUCER_EMAIL,
                           context=order_context,
                           addr_bcc=settings.SHOP_ORDER_EMAIL_BCC or None)

            # send email with payment received notification to customer
            send_mail_template("Zahlung zu Bestellung #%i erhalten" % order.id,
                           "email/customer_notification",
                           settings.SHOP_ORDER_FROM_EMAIL,
                           order.billing_detail_email,
                           context=order_context)

        return redirect('order_detail', pk=order.pk)
Exemple #22
0
def reservation_send(request):
    if not request.is_ajax():
        raise Http404()

    if request.method != 'POST':
        raise Http404()

    f = settings.RESERV_EMAIL_FROM
    t = settings.RESERV_EMAIL_TO
    if f and t:
        C = {
            'message': "Reservation request raised",
            'fields': []
        }

        for k, v in request.POST.iteritems():
            if k != 'csrfmiddlewaretoken':
                C['fields'].append((k,v,))

        send_mail_template(
            addr_from=f,
            addr_to=[t, ],
            template='email/form_response',
            subject="WEB RESERVATION REQUEST",
            context=C,
        )

    return HttpResponse("test")
def send_store_order_email(request, order):
    """
    Send order email to store on successful order.
    """
    settings.use_editable()

    address = request.session['address']
    store = request.session['stores']
    store_name = store[0].name
    store_email = [store[0].email]

    store_name_no_spaces = store_name.replace(" ", "")

    order_context = {"order": order, "request": request,
                     "order_items": order.items.all(), "address": address,
                     "store_name": store_name, "store_name_no_spaces": store_name_no_spaces}
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/store_order.html")
    except TemplateDoesNotExist:
        receipt_template = "email/store_order"
    else:
        receipt_template = "shop/email/store_order"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_STORE_ORDER_EMAIL_SUBJECT,
        receipt_template, settings.SHOP_ORDER_FROM_EMAIL,
        store_email, context=order_context,
        fail_silently=settings.DEBUG)
Exemple #24
0
    def send_email_to_operators_on_adding(self, request):
        template = "openhelpdesk/email/ticket/ticket_operators_creation"
        requester_name = _('no personal info assigned')
        if self.requester.last_name and self.requester.first_name:
            requester_name = '{} {}'.format(self.requester.first_name,
                                            self.requester.last_name)
        subject = subject_template(
            "{}_subject.html".format(template),
            {'ticket_name': self._meta.verbose_name.lower(),
             'username': self.requester.email or self.requester.username})
        try:
            site_conf = SiteConfiguration.objects.get(site=self.site)
            addr_from = site_conf.email_addr_from
            addr_to = site_conf.email_addrs_to
        except SiteConfiguration.DoesNotExist:
            addr_from = SiteConfiguration.get_no_site_email_addr_from()
            addr_to = SiteConfiguration.get_no_site_email_addrs_to()
        change_url = reverse(admin_urlname(self._meta, 'change'),
                             args=(self.pk,))

        email_background_color = (
            OrganizationSetting.email_objects.get_color(
                self.requester.email))
        context = {'ticket_name': self._meta.verbose_name, 'ticket': self,
                   'request': request, 'change_url': change_url,
                   'requester_username': self.requester.username,
                   'requester_email': self.requester.email or _(
                       'no email assigned'),
                   'requester_name': requester_name,
                   'email_background_color': email_background_color}
        send_mail_template(subject, template, addr_from, addr_to,
                           context=context, attachments=None)
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()
    order_context = {"order": order, "request": request,
                     "order_items": order.items.all()}
    if order.has_reservables:
        order_context["has_reservables"] = True
    else:
        order_context["has_reservables"] = False
    order_context["hide_shipping"] = settings.SHOP_ALWAYS_SAME_BILLING_SHIPPING
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/order_receipt.html")
    except TemplateDoesNotExist:
        receipt_template = "email/order_receipt"
    else:
        receipt_template = "shop/email/order_receipt"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_ORDER_EMAIL_SUBJECT,
                       receipt_template, settings.SHOP_ORDER_FROM_EMAIL,
                       order.billing_detail_email, context=order_context,
                       addr_bcc=settings.SHOP_ORDER_EMAIL_BCC or None)
def form_processor(request, page, response_redirect=True):
    """
    Display a built form and handle submission.
    """
    form = FormForForm(
        page.form, RequestContext(request), request.POST or None, request.FILES or None
    )
    if form.is_valid():
        url = page.get_absolute_url() + "?sent=1"
        if is_spam(request, form, url):
            return redirect(url)
        attachments = []
        for f in form.files.values():
            f.seek(0)
            attachments.append((f.name, f.read()))
        entry = form.save()
        subject = page.form.email_subject
        if not subject:
            subject = "%s - %s" % (page.form.title, entry.entry_time)
        fields = [
            (v.label, format_value(form.cleaned_data[k]))
            for (k, v) in form.fields.items()
        ]
        context = {
            "fields": fields,
            "message": page.form.email_message,
            "request": request,
        }
        email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
        email_to = form.email_to()
        if email_to and page.form.send_email:
            send_mail_template(
                subject, "email/form_response", email_from, email_to, context
            )
        headers = None
        if email_to:
            # Add the email entered as a Reply-To header
            headers = {"Reply-To": email_to}
        email_copies = split_addresses(page.form.email_copies)
        if email_copies:
            send_mail_template(
                subject,
                "email/form_response_copies",
                email_from,
                email_copies,
                context,
                attachments=attachments,
                headers=headers,
            )
        form_valid.send(sender=request, form=form, entry=entry)
        if response_redirect:
            return redirect(url)
    form_invalid.send(sender=request, form=form)
    return {"form": form}
Exemple #27
0
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()
    order_context = {"order": order, "request": request,
                     "order_items": order.items.all()}
    order_context.update(order.details_as_dict())
    from mezzanine.utils.email import send_mail_template
    send_mail_template(_("Order Receipt"), "email/order_receipt",
        settings.SHOP_ORDER_FROM_EMAIL, order.billing_detail_email,
        context=order_context, fail_silently=settings.DEBUG)
Exemple #28
0
 def save(self, team, host):
     invitation, is_new = TeamInvitation.objects.get_or_create(
         member=self.member, team=team)
     send_mail_template(_('AIChallenge team invitation'),
                        'mail/invitation_mail',
                        '',
                        self.member.email,
                        context={
                            'team': team.name,
                            'abs_link': invitation.accept_link,
                            'current_host': host
                        })
Exemple #29
0
def form_processor(request, page):
    """
    Display a built form and handle submission.
    """
    form = FormForForm(page.form, request.POST or None, request.FILES or None)
    if form.is_valid():
        url = page.get_absolute_url() + "?sent=1"
        if is_spam(request, form, url):
            return redirect(url)
        entry = form.save()
        subject = page.form.email_subject
        if not subject:
            subject = "%s - %s" % (page.form.title, entry.entry_time)
        fields = [(v.label, format_value(form.cleaned_data[k]))
                  for (k, v) in form.fields.items()]
        context = {
            "fields": fields,
            "message": page.form.email_message,
            "request": request,
        }
        email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
        email_to = form.email_to()
        if email_to and page.form.send_email:
            send_mail_template(subject,
                               "email/form_response",
                               email_from,
                               email_to,
                               context,
                               fail_silently=settings.DEBUG)
        if not settings.FORMS_DISABLE_SEND_FROM_EMAIL_FIELD:
            # Send from the email entered,
            # unless FORMS_DISABLE_SEND_FROM_EMAIL_FIELD is True.
            email_from = email_to or email_from
        email_copies = page.form.email_copies.split(",")
        email_copies = [e.strip() for e in email_copies if e.strip()]
        if email_copies:
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            send_mail_template(subject,
                               "email/form_response",
                               email_from,
                               email_copies,
                               context,
                               attachments=attachments,
                               fail_silently=settings.DEBUG)
        form_valid.send(sender=request, form=form, entry=entry)
        return redirect(url)
    form_invalid.send(sender=request, form=form)
    return {"form": form}
Exemple #30
0
def order_handler(request, order_form, order):
  """
  Default order handler - called when the order is complete and
  contains its final data. Implement your own and specify the path
  to import it from via the setting ``SHOP_HANDLER_ORDER``.
  """
  settings.use_editable()
  items = order.items.all()
  
  customer_type = 'Retail'
  user_id = order.user_id
  
  if user_id:
    try:
      user = User.objects.get(id=user_id)
    except:
      pass
    else:
      if user.has_perm('custom.wholesale_customer'):
        customer_type = 'Wholesale'

  company_name = ''
  website = ''
  fullurl = ''
  if customer_type == 'Wholesale':
    try:
      company_name = user.get_profile().company_name
      website = user.get_profile().website
    except:
      pass
    else:
      if website:
        if "http://" not in website:
          fullurl = "http://" + website
        else:
          fullurl = website

  order_context = {
    "order": order,
    "request": request,
    "order_items": items,
    "customer_type": customer_type,
    "company_name": company_name,
    "website": website,
  }
  order_context.update(order.details_as_dict())
  from mezzanine.utils.email import send_mail_template
  send_mail_template(_(customer_type + " Order Completed on manai.co.uk"), "email/order_alert",
      settings.SERVER_EMAIL, settings.DEFAULT_FROM_EMAIL,
      context=order_context, fail_silently=settings.DEBUG)
Exemple #31
0
def send_registration_confirmation_email(request):
  """
  Send order receipt email on successful order.
  """
  settings.use_editable()
  context = {"user": request.user, "site_url": settings.SITE_URL}
  template = "email/registration_confirmation"

  send_mail_template( "Thank you for registering with Manai",
                      template,
                      settings.SHOP_ORDER_FROM_EMAIL,
                      request.user.email,
                      context=context,
                      fail_silently=settings.DEBUG)
def send_invite_code_mail(code, site_url, login_url):
    context = {
        'code': code,
        'site_name': settings.SITE_TITLE,
        'site_url': site_url,
        'login_url': login_url,
    }
    send_mail_template(
        "Your Invitation to %s" % settings.SITE_TITLE,
        "invites/send_invite_email",
        settings.DEFAULT_FROM_EMAIL,
        code.registered_to,
        context=context,
        fail_silently=False,
    )
def membership_expiration_annual_check(request, user_id, date_end):
    # check on date of expiration if they had renewed
    User = get_user_model()
    user = User.objects.get(id=user_id)
    user.membership.expire_membership()
    context = {"request": request,
               # "comment_url": add_cache_bypass(comment.get_absolute_url()),
               "name": user.username,
               "end_date": date_end}
    # subject = subject_template("email/membership_expired_subject.txt", context)
    subject = _("Your membership has expired - renew asap to regain benefits!")
    send_mail_template(subject, template='email/membership_expired', addr_from=settings.DEFAULT_FROM_EMAIL,
                       addr_to=user.email,
                       context=context, attachments=None, fail_silently=None, addr_bcc=None,
                       headers=None)
Exemple #34
0
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        comment.user = request.user
        user_name = request.user.get_full_name()
        if not user_name:
            user_name = request.user.username

        comment.user_name = user_name
        # comment.email = request.user.email

        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")

        # Mezzanine's duplicate check that also checks `replied_to_id`.
        lookup = {
            "content_type": comment.content_type,
            "object_pk": comment.object_pk,
            "user_name": comment.user_name,
            "user_email": comment.user_email,
            "user_url": comment.user_url,
            "replied_to_id": comment.replied_to_id,
        }
        for duplicate in self.get_comment_model().objects.filter(**lookup):
            if (duplicate.submit_date.date() == comment.submit_date.date() and
                    duplicate.comment == comment.comment):
                return duplicate

        comment.save()
        comment_was_posted.send(sender=comment.__class__, comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        if notify_emails:
            subject = ugettext("New comment for: ") + str(obj)
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(subject, "email/comment_notification",
                               settings.DEFAULT_FROM_EMAIL, notify_emails,
                               context)
        return comment
Exemple #35
0
def send_action_to_take_email(request, user, action_type, **kwargs):
    """
    Sends an email with an action link to a user.
    The actual action takes place when the user clicks on the link

    The ``action_type`` arg is both the name of the urlpattern for
    the action link, as well as the names of the email templates
    to use. Additional context variable needed in the email template can be
    passed using the kwargs

    for action_type == 'group_membership', an instance of GroupMembershipRequest and
    instance of Group are expected to
    be passed into this function
    """
    email_to = kwargs.get('group_owner', user)
    context = {'request': request, 'user': user}
    if action_type == 'group_membership':
        membership_request = kwargs['membership_request']
        action_url = reverse(
            action_type,
            kwargs={
                "uidb36": int_to_base36(email_to.id),
                "token": default_token_generator.make_token(email_to),
                "membership_request_id": membership_request.id
            }) + "?next=" + (next_url(request) or "/")

        context['group'] = kwargs.pop('group')
    elif action_type == 'group_auto_membership':
        context['group'] = kwargs.pop('group')
        action_url = ''
    else:
        action_url = reverse(
            action_type,
            kwargs={
                "uidb36": int_to_base36(email_to.id),
                "token": default_token_generator.make_token(email_to)
            }) + "?next=" + (next_url(request) or "/")

    context['action_url'] = action_url
    context.update(kwargs)

    subject_template_name = "email/%s_subject.txt" % action_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/%s" % action_type,
                       settings.DEFAULT_FROM_EMAIL,
                       email_to.email,
                       context=context)
Exemple #36
0
def form_processor(request, page):
    """
    Display a built form and handle submission.
    """
    form = FormForForm(page.form, RequestContext(request),
                       request.POST or None, request.FILES or None)
    if form.is_valid():
        url = page.get_absolute_url() + "?sent=1"
        if is_spam(request, form, url):
            return redirect(url)
        attachments = []
        for f in form.files.values():
            f.seek(0)
            attachments.append((f.name, f.read()))
        entry = form.save()
        subject = page.form.email_subject
        if not subject:
            subject = "%s - %s" % (page.form.title, entry.entry_time)
        fields = [(v.label, format_value(form.cleaned_data[k]))
                  for (k, v) in form.fields.items()]
        context = {
            "fields": fields,
            "message": page.form.email_message,
            "request": request,
            "page": page,
            "entry_id": entry.id,
        }

        url += '&entry_id=' + str(entry.pk)

        email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
        email_to = form.email_to()
        if email_to and page.form.send_email:
            send_mail_template(subject, "email/form_response", email_from,
                               email_to, context)
        headers = None
        if email_to:
            # Add the email entered as a Reply-To header
            headers = {'Reply-To': email_to}
        email_copies = split_addresses(page.form.email_copies)
        if email_copies:
            send_mail_template(subject, "email/form_response_copies",
                               email_from, email_copies, context,
                               attachments=attachments, headers=headers)
        form_valid.send(sender=request, form=form, entry=entry)
        return redirect(url)
    form_invalid.send(sender=request, form=form)
    return {"form": form}
def send_reminder_email(user,subject):
    """
    Send order receipt email on successful order.
    """ 
    settings.use_editable()
    site = Site.objects.get_current()
    url= site.domain+'/member-services/join-ipra/'
    order_context = {"user": user,"update_url":url,"subject":subject}
    #order_context.update(order.details_as_dict())

    receipt_template = "email/account_reminder"

    send_mail_template(subject,
                       receipt_template, 'IPRA <*****@*****.**>',
                       user.email, context=order_context,
                       addr_bcc=None)
    def send_email_to_requester(self, request):
        template = "openhelpdesk/email/report/info_to_request"
        context = {'report_name': self._meta.verbose_name.lower(),
                   'operator': request.user.username,
                   'ticket_id': self.ticket_id}

        subject = subject_template("{}_subject.html".format(template), context)
        addr_from = request.user.email
        addr_to = [self.ticket.requester.email]
        change_ticket_url = '{}#tab_messages'.format(
            reverse(admin_urlname(self.ticket._meta, 'change'),
                    args=(self.ticket_id,)))
        context.update({'report': self, 'request': request,
                        'change_ticket_url': change_ticket_url})
        send_mail_template(subject, template, addr_from, addr_to,
                           context=context, attachments=None)
Exemple #39
0
def suggest_store(request, template="blog/suggest_store.html"):
	if request.is_ajax():
		if request.method == 'POST':
			form = SuggestStoreForm(request.POST)
			if form.is_valid():
				data = json.dumps({'success':True})
				response_kwargs = {"content_type": 'application/json'}
				email_from = settings.DEFAULT_FROM_EMAIL
				email_to = settings.SUGGEST_STORE_EMAIL_TO
				subject = form.cleaned_data['email_subject']
				message = form.cleaned_data['email_message']
				sender_email = "Anonymous"
				if request.user.is_authenticated(): 
					sender_email = request.user.email

				context = {
					"message": message,
					"request": request,
					"from_email": sender_email
				}
				if email_to and email_from:
					send_mail_template(subject, "email/suggest_store_response", email_from,
						email_to, context, fail_silently=settings.DEBUG)

				return HttpResponse(data, **response_kwargs)
			elif form.errors:
				data = json.dumps(form.errors)
				response_kwargs = {"content_type": 'application/json', "status": 400}
				return HttpResponse(data, **response_kwargs)
		else:
			form = SuggestStoreForm()
			if request.user.is_authenticated():
				form.fields['email_from'].initial = request.user.email
			else:
				form.fields['email_from'].initial = settings.SERVER_EMAIL
			form.fields['email_subject'].initial = settings.SUGGEST_STORE_EMAIL_SUBJECT
			form.fields['email_from'].label = ''
			form.fields['email_subject'].label = ''
			form.fields['email_message'].label = 'Store Name or Link'

			form.fields['email_from'].widget.attrs['style'] = 'display:none'
			form.fields['email_subject'].widget.attrs['style'] = 'display:none'
			context = {"form": form, "action_url": reverse("suggest_store")}
			response = render(request, template, context)
			return response
	else:
		raise Http404()
def ajax_form_processor(request, page):
    """
    Handle a Mezzanine form submissions if and only if the request
    is ajax, otherwise the default processor will run.
    """
    if request.is_ajax():
        form = FormForForm(page.form, RequestContext(request),
                           request.POST or None, request.FILES or None)
        if form.is_valid():
            form.save()
            url = page.get_absolute_url() + "?sent=1"
            if is_spam(request, form, url):
                return redirect(url)
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            entry = form.save()
            subject = page.form.email_subject
            if not subject:
                subject = "%s - %s" % (page.form.title, entry.entry_time)
            fields = [(v.label, format_value(form.cleaned_data[k]))
                      for (k, v) in form.fields.items()]
            context = {
                "fields": fields,
                "message": page.form.email_message,
                "request": request,
            }
            email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form.email_to()
            if email_to and page.form.send_email:
                send_mail_template(subject, "email/form_response", email_from,
                                   email_to, context)
            headers = None
            if email_to:
                # Add the email entered as a Reply-To header
                headers = {'Reply-To': email_to}
            email_copies = split_addresses(page.form.email_copies)
            if email_copies:
                send_mail_template(subject, "email/form_response_copies",
                                   email_from, email_copies, context,
                                   attachments=attachments, headers=headers)
            form_valid.send(sender=request, form=form, entry=entry)
            return render(request, 'includes/form_content_only.html', {'form': form, 'ok': True})
        else:
            form_invalid.send(sender=request, form=form)
            return  render(request, 'includes/form_content_only.html', {'form': form})
Exemple #41
0
    def save(self, request):
        """
        Saves a new comment and sends any notification emails.
        """
        comment = self.get_comment_object()
        obj = comment.content_object
        if is_authenticated(request.user):
            comment.user = request.user
        comment.by_author = request.user == getattr(obj, "user", None)
        comment.ip_address = ip_for_request(request)
        comment.replied_to_id = self.data.get("replied_to")

        # Mezzanine's duplicate check that also checks `replied_to_id`.
        lookup = {
            "content_type": comment.content_type,
            "object_pk": comment.object_pk,
            "user_name": comment.user_name,
            "user_email": comment.user_email,
            "user_url": comment.user_url,
            "replied_to_id": comment.replied_to_id,
        }
        for duplicate in self.get_comment_model().objects.filter(**lookup):
            if (duplicate.submit_date.date() == comment.submit_date.date()
                    and duplicate.comment == comment.comment):
                return duplicate

        comment.save()
        comment_was_posted.send(sender=comment.__class__,
                                comment=comment,
                                request=request)
        notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
        if notify_emails:
            subject = ugettext("New comment for: ") + str(obj)
            context = {
                "comment": comment,
                "comment_url": add_cache_bypass(comment.get_absolute_url()),
                "request": request,
                "obj": obj,
            }
            send_mail_template(
                subject,
                "email/comment_notification",
                settings.DEFAULT_FROM_EMAIL,
                notify_emails,
                context,
            )
        return comment
def ajax_form_processor(request, page):
    """
    Handle a Mezzanine form submissions if and only if the request
    is ajax, otherwise the default processor will run.
    """
    if request.is_ajax():
        form = FormForForm(page.form, RequestContext(request), request.POST or None, request.FILES or None)
        if form.is_valid():
            form.save()
            url = page.get_absolute_url() + "?sent=1"
            if is_spam(request, form, url):
                return redirect(url)
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            entry = form.save()
            subject = page.form.email_subject
            if not subject:
                subject = "%s - %s" % (page.form.title, entry.entry_time)
            fields = [(v.label, format_value(form.cleaned_data[k])) for (k, v) in form.fields.items()]
            context = {"fields": fields, "message": page.form.email_message, "request": request}
            email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form.email_to()
            if email_to and page.form.send_email:
                send_mail_template(subject, "email/form_response", email_from, email_to, context)
            headers = None
            if email_to:
                # Add the email entered as a Reply-To header
                headers = {"Reply-To": email_to}
            email_copies = split_addresses(page.form.email_copies)
            if email_copies:
                send_mail_template(
                    subject,
                    "email/form_response_copies",
                    email_from,
                    email_copies,
                    context,
                    attachments=attachments,
                    headers=headers,
                )
            form_valid.send(sender=request, form=form, entry=entry)
            return render(request, "includes/form_content_only.html", {"form": form, "ok": True})
        else:
            form_invalid.send(sender=request, form=form)
            return render(request, "includes/form_content_only.html", {"form": form})
Exemple #43
0
def contact_us(request, template="generic/contact_us.html"):
	if request.is_ajax():
		if request.method == 'POST':
			form = ContactUsForm(request.POST)
			if form.is_valid():
				data = json.dumps({'success':True})
				response_kwargs = {"content_type": 'application/json'}
				
				email_from = settings.DEFAULT_FROM_EMAIL
				email_to = settings.CONTACT_US_EMAIL_TO

				subject = form.cleaned_data['email_subject']
				message = form.cleaned_data['email_contact_message']
				sender_email = "Anonymous"
				if request.user.is_authenticated(): 
					sender_email = request.user.email

				context = {
					"message": message,
					"request": request,
					"from_email": sender_email
				}
				if email_to and email_from:
					send_mail_template(subject, "email/contact_us", email_from,
						email_to, context, fail_silently=settings.DEBUG)

				return HttpResponse(data, **response_kwargs)
			elif form.errors:
				data = json.dumps(form.errors)
				response_kwargs = {"content_type": 'application/json', "status": 400}
				return HttpResponse(data, **response_kwargs)
		else:
			form = ContactUsForm()
			form.fields['email_contact_message'].widget.attrs['style'] = 'resize:none;'
			if request.user.is_authenticated():
				form.fields['email_from'].initial = request.user.email
			else:
				form.fields['email_from'].initial = settings.SERVER_EMAIL
				form.fields['email_from'].widget.attrs['style'] = 'display:none'

			context = {"form": form, "action_url": reverse("contact_us")}
			response = render(request, template, context)
			return response
	else:
		raise Http404()
Exemple #44
0
 def send_emails_on_creation(self, request):
     for template, addr_to in [
         ('booking_created_booker', self.booker.email),
         ('booking_created_operator',
          self.slottime.booking_type.get_notification_emails())]:
         try:
             send_mail_template(
                 subject_template(
                     'nowait/email/subject/{}.txt'.format(template), None),
                 'nowait/email/{}'.format(template), settings.SERVER_EMAIL,
                 addr_to, context={'booking': self,
                                   'request': request})
         except SMTPException as e:
             logger = logging.getLogger('django.request')
             logger.error(
                 'Internal Server Error: %s', request.path,
                 exc_info=str(e),
                 extra={'status_code': 500, 'request': request})
def alert_membership_expiration_near(request, user_id, date_end):
    """
    sends notification email to user warning them that their membership expires on end_date, but nothing else
    :param id:
    :param user_id:
    :param end_date:
    :return:
    """
    User = get_user_model()
    user = User.objects.get(id=user_id)
    context = {"name":user.username,
               "request": request,
               "end_date":date_end}
    # subject = subject_template("email/membership_alert_subject.txt", context)
    subject = _("Your membership is about to expire")
    send_mail_template(subject, template='email/membership_alert', addr_from=settings.DEFAULT_FROM_EMAIL, addr_to=user.email,
                       context=context, attachments=None, fail_silently=None, addr_bcc=None,
                       headers=None)
Exemple #46
0
    def notify_to_operator(self, request):
        template = "openhelpdesk/email/message/notify_to_operator"
        context = {
            'message_verbose_name':
            self._meta.verbose_name.lower(),
            'message_from':
            '{} {}'.format(self.sender.last_name.capitalize(),
                           self.sender.first_name.capitalize()),
            'message_from_email':
            self.sender.email,
            'email_background_color':
            (OrganizationSetting.email_objects.get_color(self.sender.email))
        }

        try:
            site_conf = SiteConfiguration.objects.get(site=self.ticket.site)
            addr_from = site_conf.email_addr_from
        except (SiteConfiguration.DoesNotExist, Ticket.DoesNotExist):
            addr_from = SiteConfiguration.get_no_site_email_addr_from()

        subject = subject_template("{}_subject.html".format(template), context)
        # TODO: gestire la questione del destinatario
        addr_to = '*****@*****.**'
        if self.ticket.assignee:
            addr_to = self.ticket.assignee.email
        ticket_url = 'http://{}{}'.format(
            request.get_host(),
            reverse(admin_urlname(self.ticket._meta, 'change'),
                    args=(self.ticket_id, )))
        context.update({
            'request': request,
            'ticket_url': ticket_url,
            'message_url': ticket_url + "#tab_messages",
            'ticket_id': self.ticket.id,
            'content': self.content,
            'ticket_status': self.ticket.status
        })

        send_mail_template(subject,
                           template,
                           addr_from,
                           addr_to,
                           context=context,
                           attachments=None)
def form_processor(request, page):
    """
    Display a built form and handle submission.
    """
    form = FormForForm(page.form, request.POST or None, request.FILES or None)
    if form.is_valid():
        url = page.get_absolute_url() + "?sent=1"
        if is_spam(request, form, url):
            return redirect(url)
        entry = form.save()
        subject = page.form.email_subject
        if not subject:
            subject = "%s - %s" % (page.form.title, entry.entry_time)
        fields = [(v.label, format_value(form.cleaned_data[k]))
                  for (k, v) in form.fields.items()]
        context = {
            "fields": fields,
            "message": page.form.email_message,
            "request": request,
        }
        email_from = page.form.email_from or settings.DEFAULT_FROM_EMAIL
        email_to = form.email_to()
        if email_to and page.form.send_email:
            send_mail_template(subject, "email/form_response", email_from,
                               email_to, context, fail_silently=settings.DEBUG)
        if not settings.FORMS_DISABLE_SEND_FROM_EMAIL_FIELD:
            # Send from the email entered,
            # unless FORMS_DISABLE_SEND_FROM_EMAIL_FIELD is True.
            email_from = email_to or email_from
        email_copies = page.form.email_copies.split(",")
        email_copies = [e.strip() for e in email_copies if e.strip()]
        if email_copies:
            attachments = []
            for f in form.files.values():
                f.seek(0)
                attachments.append((f.name, f.read()))
            send_mail_template(subject, "email/form_response", email_from,
                               email_copies, context, attachments=attachments,
                               fail_silently=settings.DEBUG)
        form_valid.send(sender=request, form=form, entry=entry)
        return redirect(url)
    form_invalid.send(sender=request, form=form)
    return {"form": form}
Exemple #48
0
def ipn(request):

    api = PolyBanking(settings.POLYBANKING_SERVER, settings.POLYBANKING_ID, settings.POLYBANKING_KEY_REQUEST, settings.POLYBANKING_KEY_IPN, settings.POLYBANKING_KEY_API)

    ok, message, ref, status, status_ok, date = api.check_ipn(request.POST)

    if ok:

        payment = get_object_or_404(Payment, pk=ref.split('-')[-1])
        payment.is_valid = status_ok
        payment.save()

        entry = payment.entry

        subject = payment.entry.form.final_confirmation_subject

        context = {
            "message": payment.entry.form.final_confirmation_email,
        }

        if status_ok:

            email_from = payment.entry.form.email_from or settings.DEFAULT_FROM_EMAIL

            for field in payment.entry.form.fields.all():
                if field.field_type == EMAIL:
                    email_to = payment.entry.fields.filter(field_id=field.id).first().value


            if email_to and payment.entry.form.send_email:
                send_mail_template(subject, "email/form_response_paid", email_from,
                                   email_to, context)
            headers = None
            if email_to:
                # Add the email entered as a Reply-To header
                headers = {'Reply-To': email_to}
            email_copies = split_addresses(payment.entry.form.email_copies)
            if email_copies:
                send_mail_template(subject, "email/form_response_copies_paid",
                                   email_from, email_copies, context, headers=headers)


    return HttpResponse('')
def question_and_answer_page_processor(request, page):
    if request.method == 'POST':
        url = page.get_absolute_url() + "?sent=1"

        question_form = AskedQuestionForm(data=request.POST)
        question = question_form.save(page.qapage, request.user)

        fields = [('questioner', question.questioner), ('question', question.question)]

        responder_mail = split_addresses(page.qapage.responder_mail)
        if responder_mail:
            send_mail_template(page.title, 'email/form_response', None, responder_mail,
                               context={'message': _('A new question is waiting for you!'), 'fields': fields})

        return redirect(url)


    question_form = AskedQuestionForm()
    return {'form': question_form}
 def send_email_to_operators_on_adding(self, request):
     template = "openhelpdesk/email/ticket/ticket_operators_creation"
     subject = subject_template(
         "{}_subject.html".format(template),
         {'ticket_name': self._meta.verbose_name.lower(),
          'username': self.requester.username})
     try:
         site_conf = SiteConfiguration.objects.get(site=self.site)
         addr_from = site_conf.email_addr_from
         addr_to = site_conf.email_addrs_to
     except SiteConfiguration.DoesNotExist:
         addr_from = SiteConfiguration.get_no_site_email_addr_from()
         addr_to = SiteConfiguration.get_no_site_email_addrs_to()
     change_url = reverse(admin_urlname(self._meta, 'change'),
                          args=(self.pk,))
     context = {'ticket_name': self._meta.verbose_name, 'ticket': self,
                'request': request, 'change_url': change_url}
     send_mail_template(subject, template, addr_from, addr_to,
                        context=context, attachments=None)
Exemple #51
0
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.clear_cache()
    order_context = {
        "order": order,
        "request": request,
        "order_items": order.items.all(),
    }
    order_context.update(order.details_as_dict())
    receipt_template = "email/order_receipt"
    send_mail_template(
        settings.SHOP_ORDER_EMAIL_SUBJECT,
        receipt_template,
        settings.SHOP_ORDER_FROM_EMAIL,
        order.billing_detail_email,
        context=order_context,
        addr_bcc=settings.SHOP_ORDER_EMAIL_BCC or None,
    )
Exemple #52
0
def send_order_email(request, order):
    """
    Send order receipt email on successful order.
    """
    settings.use_editable()
    order_context = {"order": order, "request": request,
                     "order_items": order.items.all()}
    order_context.update(order.details_as_dict())
    try:
        get_template("shop/email/order_receipt.html")
    except TemplateDoesNotExist:
        receipt_template = "email/order_receipt"
    else:
        receipt_template = "shop/email/order_receipt"
        from warnings import warn
        warn("Shop email receipt templates have moved from "
             "templates/shop/email/ to templates/email/")
    send_mail_template(settings.SHOP_ORDER_EMAIL_SUBJECT,
        receipt_template, settings.SHOP_ORDER_FROM_EMAIL,
        order.billing_detail_email, context=order_context,
        fail_silently=settings.DEBUG)
 def handle(self, *args, **ops):
     count = 0
     verification_type = "signup_verify"
     request = {'get_host': 'aichallenge.sharif.edu:2016'}
     for user in tqdm(Member.objects.filter(is_active=False), leave=False):
         verify_url = reverse(verification_type, kwargs={
             "uidb36": int_to_base36(user.id),
             "token": default_token_generator.make_token(user),
         }) + "?next=" + "/"
         context = {
             "request": request,
             "user": user,
             "verify_url": verify_url,
         }
         subject_template_name = "email/%s_subject.txt" % verification_type
         subject = subject_template(subject_template_name, context)
         send_mail_template(subject, "email/%s" % verification_type,
                            settings.DEFAULT_FROM_EMAIL, user.email,
                            context=context)
         count += 1
     self.stdout.write("resent %d verification email" % count)
Exemple #54
0
def create(request):
    user = request.user
    # User must belong to an organization
    organization = require_organization(request, None)
    if isinstance(organization, HttpResponseRedirect):
        return organization
    initial = {'user': request.user}
    if not organization.liaisons.count():
        user = request.user
        liaison = Liaison.objects.create(name=(user.get_full_name()
                                               or user.username),
                                         email=user.email,
                                         organization=organization)
        initial['liaison'] = liaison
    cat = _category_by_model(Project)
    initial['category'] = cat
    form = ProjectForm(request.POST or None,
                       request.FILES or None,
                       initial=initial)
    if request.method == 'POST' and form.is_valid():
        form.save()
        action = 'creating'
        project = form.instance
        send_mail_template('ARX Project created: %s' % project.title,
                           'sfpirg/email/arx_draft',
                           Settings.get_setting('SERVER_EMAIL'),
                           request.user.email,
                           context=locals(),
                           attachments=None,
                           fail_silently=settings.DEBUG,
                           addr_bcc=None)
        if project.is_submitted:
            send_mail_template('ARX Project submitted: %s' % project.title,
                               'sfpirg/email/arx_submitted',
                               Settings.get_setting('SERVER_EMAIL'),
                               request.user.email,
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
            send_mail_template('ARX Project submitted: %s' % project.title,
                               'sfpirg/email/arx_admin_submitted',
                               Settings.get_setting('SERVER_EMAIL'),
                               Settings.get_setting('ARX_ADMIN_EMAIL'),
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
        messages.info(
            request,
            'Thank you! Please check your email for a confirmation message. Check your spam folder if you don\'t see it. We will get back to you very soon.'
        )
        return HttpResponseRedirect(form.instance.get_absolute_url())
    log.debug('Form errors: %s' % form.errors)
    user = request.user
    current_item = 'Create Project'
    context = RequestContext(request, locals())
    return render_to_response('sfpirg/arx_project_create.html', {},
                              context_instance=context)
Exemple #55
0
def multi_apply(request):
    form = MultiApplicationForm()
    project_ids = request.session.get(SELECTED_PROJECTS, [])
    count = len(project_ids)
    current_item = 'Apply for Projects'
    projects = Project.objects.filter(pk__in=project_ids)
    if request.method == 'POST':
        form = MultiApplicationForm(request.POST)
        name = form.data['name']
        email = form.data['email']
        comments = form.data['message']
        if form.is_valid():
            request.session[SELECTED_PROJECTS] = []
            for proj_id in project_ids:
                Application.objects.create(name=name,
                                           email=email,
                                           project_id=proj_id,
                                           message=comments)
            send_mail_template('ARX Project application submitted',
                               'sfpirg/email/arx_application',
                               Settings.get_setting('SERVER_EMAIL'),
                               email,
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
            send_mail_template('ARX Project application submitted',
                               'sfpirg/email/arx_admin_application',
                               Settings.get_setting('SERVER_EMAIL'),
                               Settings.get_setting('ARX_ADMIN_EMAIL'),
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
            return HttpResponseRedirect(resolve_url('thankyou'))
    context = RequestContext(request, locals())
    return render_to_response('sfpirg/arx_multi_projects_apply.html', {},
                              context_instance=context)
Exemple #56
0
def project(request, slug):
    user = request.user
    project = get_object_or_404(Project, slug=slug)
    was_submitted = project.is_submitted
    form = None
    if 'edit' in request.REQUEST:
        # User must belong to an organization
        organization = require_organization(request, project)
        if isinstance(organization, HttpResponseRedirect):
            return organization
        if request.method == 'POST':
            form = ProjectForm(request.POST, request.FILES, instance=project)
            if form.is_valid():
                form.save()
                if not project.is_submitted:
                    # Project draft was saved.
                    action = 'updating'
                    send_mail_template('ARX Project updated: %s' %
                                       project.title,
                                       'sfpirg/email/arx_draft',
                                       Settings.get_setting('SERVER_EMAIL'),
                                       project.user.email,
                                       context=locals(),
                                       attachments=None,
                                       fail_silently=settings.DEBUG,
                                       addr_bcc=None)
                elif not was_submitted:
                    # Project was not submitted before, but now it is.
                    send_mail_template('ARX Project submitted: %s' %
                                       project.title,
                                       'sfpirg/email/arx_submitted',
                                       Settings.get_setting('SERVER_EMAIL'),
                                       project.user.email,
                                       context=locals(),
                                       attachments=None,
                                       fail_silently=settings.DEBUG,
                                       addr_bcc=None)
                    send_mail_template('ARX Project submitted: %s' %
                                       project.title,
                                       'sfpirg/email/arx_admin_submitted',
                                       Settings.get_setting('SERVER_EMAIL'),
                                       Settings.get_setting('ARX_ADMIN_EMAIL'),
                                       context=locals(),
                                       attachments=None,
                                       fail_silently=settings.DEBUG,
                                       addr_bcc=None)
                messages.info(
                    request,
                    'Thank you! Please check your email for a confirmation message. Check your spam folder if you don\'t see it. We will get back to you very soon.'
                )
                return HttpResponseRedirect(project.get_absolute_url())
        else:
            form = ProjectForm(instance=project)
    page = project
    current_item = page.title
    context = RequestContext(request, locals())
    return render_to_response('sfpirg/arx_project.html', {},
                              context_instance=context)
Exemple #57
0
def add_testimonial(request):
    form = None
    if request.method == 'POST':
        form = TestimonialForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            testimonial = form.instance
            send_mail_template('New experience submitted: %s' %
                               form.instance.title,
                               'sfpirg/email/experience_admin',
                               Settings.get_setting('SERVER_EMAIL'),
                               Settings.get_setting('ARX_ADMIN_EMAIL'),
                               context=locals(),
                               attachments=None,
                               fail_silently=settings.DEBUG,
                               addr_bcc=None)
            if form.cleaned_data.get('author_email'):
                send_mail_template('Your experience submitted: %s' %
                                   form.instance.title,
                                   'sfpirg/email/experience_user',
                                   Settings.get_setting('SERVER_EMAIL'),
                                   form.cleaned_data.get('author_email'),
                                   context=locals(),
                                   attachments=None,
                                   fail_silently=settings.DEBUG,
                                   addr_bcc=None)
            return HttpResponseRedirect(resolve_url('thankyou'))
    else:
        form = TestimonialForm(
            initial={
                'category': _category_by_model(Testimonial),
                'status': 1,
                '_order': 0,
            })
    current_item = 'Add Testimonial'
    context = RequestContext(request, locals())
    return render_to_response('sfpirg/add_testimonial.html', {},
                              context_instance=context)