Ejemplo n.º 1
0
def message(request, group_slug, template_name="user_groups/message.html"):
    """
    Send a message to the group
    """
    from tendenci.apps.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(group=group, status=True, status_detail="active")

    num_members = members.count()

    form = MessageForm(request.POST or None, request=request, num_members=num_members)

    if request.method == "POST" and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting("site", "global", "siteemailnoreplyaddress")
        email.reply_to = email.sender
        email.content_type = email.CONTENT_TYPE_HTML
        email.subject = form.cleaned_data["subject"]
        email.body = form.cleaned_data["body"]
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data["is_test"]:
            email.recipient = request.user.email
            email.send()

            messages.add_message(request, messages.SUCCESS, _("Successfully sent test email to yourself"))

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                email.recipient = member.member.email
                email.send()

            messages.add_message(
                request,
                messages.SUCCESS,
                _("Successfully sent email to all %(num)s members in this group" % {"num": num_members}),
            )

            EventLog.objects.log(instance=email)

        return redirect("group.detail", group_slug=group_slug)

    else:
        print "form errors", form.errors.items()

    return render(request, template_name, {"group": group, "num_members": num_members, "form": form})
Ejemplo n.º 2
0
        def email_script_errors(err_msg):
            """Send error message to us in case of an error.
            """
            email = Email()
            email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
            email.sender_display = get_setting('site', 'global', 'sitedisplayname')
            site_url = get_setting('site', 'global', 'siteurl')

            now = datetime.now()
            nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = 'Error Setting Up Campaign Monitor Account on New Site %s' % site_url

                email.send()
        def email_script_errors(err_msg):
            """Send error message to us in case of an error.
            """
            email = Email()
            email.sender = get_setting('site', 'global',
                                       'siteemailnoreplyaddress')
            email.sender_display = get_setting('site', 'global',
                                               'sitedisplayname')
            site_url = get_setting('site', 'global', 'siteurl')

            now = datetime.now()
            nowstr = time.strftime("%d-%b-%y %I:%M %p", now.timetuple())
            email.recipient = get_script_support_emails()
            if email.recipient:
                email.body = '%s \n\nTime Submitted: %s\n' % (err_msg, nowstr)
                email.content_type = "text"
                email.subject = 'Error Setting Up Campaign Monitor Account on New Site %s' % site_url

                email.send()
    def send_organizer_confirmation(self, event):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.site_settings.utils import get_setting

        email = Email()
        if event.organizer and event.organizer.user \
            and event.organizer.user.email:
            email.recipient = event.organizer.user.email
        else:
            email.recipient = get_setting('module', 'events', 'admin_emails')
            if not email.recipient:
                email.recipient = get_setting('site', 'global',
                                              'sitecontactemail')

        email.subject = '%s Event Reminders Distributed for: %s' % (
            get_setting('site', 'global', 'sitedisplayname'), event.title)
        email.body = self.get_reminder_conf_body(event)

        email.send()
Ejemplo n.º 5
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        subject = ''
        subj = data.get('subject', '')
        inc_last_name = data.get('personalize_subject_last_name')
        inc_first_name = data.get('personalize_subject_first_name')

        if inc_first_name and not inc_last_name:
            subject = '[firstname] ' + subj
        elif inc_last_name and not inc_first_name:
            subject = '[lastname] ' + subj
        elif inc_first_name and inc_last_name:
            subject = '[firstname] [lastname] ' + subj
        else:
            subject = subj
        nl = super(OldGenerateForm, self).save(*args, **kwargs)
        nl.subject = subject
        nl.actionname = subject
        nl.date_created = datetime.datetime.now()
        nl.send_status = 'draft'
        if nl.default_template:
            template = render_to_string(template_name=nl.default_template,
                                        request=self.request)
            email_content = nl.generate_newsletter(self.request, template)

            email = Email()
            email.subject = subject
            email.body = email_content
            email.sender = get_setting('site', 'global',
                                       'siteemailnoreplyaddress')
            email.sender_display = self.request.user.profile.get_name()
            email.reply_to = self.request.user.email
            email.creator = self.request.user
            email.creator_username = self.request.user.username
            email.owner = self.request.user
            email.owner_username = self.request.user.username
            email.save()
            nl.email = email

        nl.save()

        return nl
Ejemplo n.º 6
0
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        subject = ''
        subj = data.get('subject', '')
        inc_last_name = data.get('personalize_subject_last_name')
        inc_first_name = data.get('personalize_subject_first_name')

        if inc_first_name and not inc_last_name:
            subject = '[firstname] ' + subj
        elif inc_last_name and not inc_first_name:
            subject = '[lastname] ' + subj
        elif inc_first_name and inc_last_name:
            subject = '[firstname] [lastname] ' + subj
        else:
            subject = subj
        nl = super(OldGenerateForm, self).save(*args, **kwargs)
        nl.subject = subject
        nl.actionname = subject
        nl.date_created = datetime.datetime.now()
        nl.send_status = 'draft'
        if nl.default_template:
            template = render_to_string(nl.default_template, context_instance=RequestContext(self.request))
            email_content = nl.generate_newsletter(self.request, template)

            email = Email()
            email.subject = subject
            email.body = email_content
            email.sender = self.request.user.email
            email.sender_display = self.request.user.profile.get_name()
            email.reply_to = self.request.user.email
            email.creator = self.request.user
            email.creator_username = self.request.user.username
            email.owner = self.request.user
            email.owner_username = self.request.user.username
            email.save()
            nl.email = email

        nl.save()

        return nl
Ejemplo n.º 7
0
    def send_organizer_confirmation(self, event):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.site_settings.utils import get_setting

        email = Email()
        if event.organizer and event.organizer.user \
            and event.organizer.user.email:
            email.recipient = event.organizer.user.email
        else:
            email.recipient = get_setting('module', 'events', 'admin_emails')
            if not email.recipient:
                email.recipient = get_setting('site', 'global',
                                              'sitecontactemail')

        email.subject = '%s Event Reminders Distributed for: %s' % (
                                get_setting('site', 'global',
                                            'sitedisplayname'),
                                event.title
                                )
        email.body = self.get_reminder_conf_body(event)

        email.send()
Ejemplo n.º 8
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user, 'forms.view_form', form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(
            field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(
                request, messages.WARNING,
                'Please edit the form to include an email field ' +
                'as it is required for setting up a recurring ' +
                'payment for anonymous users.')

    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated:
            billing_form.initial = {
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email
            }
    else:
        billing_form = None

    form_for_form = FormForForm(form, request.user, request.session,
                                request.POST or None, request.FILES or None)

    if get_setting('site', 'global', 'captcha'):  # add captcha
        if billing_form:
            # append the captcha to the end of the billing form
            captcha_field = CustomCatpchaField(label=_('Type the code below'))
            if 'captcha' in form_for_form.fields:
                form_for_form.fields.pop('captcha')
            billing_form.fields['captcha'] = captcha_field

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form
                                         or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous:
                entry.creator = entry.check_and_create_user()
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To': form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(
                entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(
                    email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=getattr(settings,
                                                 'EMAIL_FAIL_SILENTLY', True))
                # log an event
                EventLog.objects.log(
                    instance=form,
                    description='Confirmation email sent to {}'.format(
                        email_to))

            # Email copies to admin
            admin_body = generate_admin_email_body(entry,
                                                   form_for_form,
                                                   user=request.user)
            email_from = email_to or email_from  # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To': email_from})
            email_copies = [
                e.strip() for e in form.email_copies.split(',') if e.strip()
            ]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                # Commenting out the attachment block to not add attachments to the email for the reason below:
                # According to SES message quotas https://docs.aws.amazon.com/ses/latest/DeveloperGuide/quotas.html,
                # the maximum message size (including attachments) is 10 MB per message (after base64 encoding)
                # which means the actual size should be less than 7.5 MB or so because text after encoded with the BASE64
                # algorithm increases its size by 1/3. But the allowed upload size is much larger than 7.5 MB.
                #                 try:
                #                     for f in form_for_form.files.values():
                #                         f.seek(0)
                #                         attachments.append((f.name, f.read()))
                #                 except ValueError:
                #                     attachments = []
                #                     for field_entry in entry.fields.all():
                #                         if field_entry.field.field_type == 'FileField':
                #                             try:
                #                                 f = default_storage.open(field_entry.value)
                #                             except IOError:
                #                                 pass
                #                             else:
                #                                 f.seek(0)
                #                                 attachments.append((f.name.split('/')[-1], f.read()))

                fail_silently = getattr(settings, 'EMAIL_FAIL_SILENTLY', True)
                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    #                     if request.user.is_anonymous or not request.user.is_active:
                    #                         email.content_type = 'text'
                    email.send(fail_silently=fail_silently,
                               attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=fail_silently,
                               attachments=attachments)

            # payment redirect
            if (form.custom_payment
                    or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get(
                    'custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous:
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(
                            1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                        user=rp_user,
                        description=form.title,
                        billing_period=entry.pricing.billing_period,
                        billing_start_dt=billing_start_dt,
                        num_days=entry.pricing.num_days,
                        due_sore=entry.pricing.due_sore,
                        payment_amount=price,
                        taxable=entry.pricing.taxable,
                        tax_rate=entry.pricing.tax_rate,
                        has_trial_period=entry.pricing.has_trial_period,
                        trial_period_start_dt=trial_period_start_dt,
                        trial_period_end_dt=trial_period_end_dt,
                        trial_amount=entry.pricing.trial_amount,
                        creator=rp_user,
                        creator_username=rp_user.username,
                        owner=rp_user,
                        owner_username=rp_user.username,
                    )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS,
                                         _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id,
                                    rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if invoice.balance > 0:
                        if (entry.payment_method.machine_name
                            ).lower() == 'credit-card':
                            return redirect('payment.pay_online', invoice.id,
                                            invoice.guid)
                        # redirect to invoice page
                        return redirect('invoice.view', invoice.id,
                                        invoice.guid)

            # default redirect
            if form.completion_url:
                completion_url = form.completion_url.strip().replace(
                    '[entry_id]', str(entry.id))
                return HttpResponseRedirect(completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_resp(request=request,
                          template_name=template,
                          context=context)
Ejemplo n.º 9
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' +
                    'as it is required for setting up a recurring ' +
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated:
            billing_form.initial = {
                        'first_name':request.user.first_name,
                        'last_name':request.user.last_name,
                        'email':request.user.email}
    else:
        billing_form = None

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous:
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To':form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous:
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id, rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if (entry.payment_method.machine_name).lower() == 'credit-card':
                        return redirect('payment.pay_online', invoice.id, invoice.guid)
                    # redirect to invoice page
                    return redirect('invoice.view', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url.strip())
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_resp(request=request, template_name=template, context=context)
Ejemplo n.º 10
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.apps.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(
        group=group,
        status=True,
        status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
        request=request,
        num_members=num_members)


    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = 'text/html'
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            email.send()

            messages.add_message(
                request,
                messages.SUCCESS,
                _('Successfully sent test email to yourself'))

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                email.recipient = member.member.email
                email.send()

            messages.add_message(
                request,
                messages.SUCCESS,
                _('Successfully sent email to all %(num)s members in this group' % {'num': num_members}))

            EventLog.objects.log(instance=email)

        return redirect('group.detail', group_slug=group_slug)

    else:
        print 'form errors', form.errors.items()


    return render(request, template_name, {
        'group': group,
        'num_members': num_members,
        'form': form})
Ejemplo n.º 11
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.apps.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(group=group,
                                             status=True,
                                             status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
                       request=request,
                       num_members=num_members)

    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = email.CONTENT_TYPE_HTML
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            email.send()

            messages.add_message(request, messages.SUCCESS,
                                 _('Successfully sent test email to yourself'))

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                email.recipient = member.member.email
                email.send()

            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully sent email to all %(num)s members in this group'
                  % {'num': num_members}))

            EventLog.objects.log(instance=email)

        return redirect('group.detail', group_slug=group_slug)

    else:
        print('form errors', list(form.errors.items()))

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={
                              'group': group,
                              'num_members': num_members,
                              'form': form
                          })
Ejemplo n.º 12
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user, 'forms.view_form', form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(
            field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(
                request, messages.WARNING,
                'Please edit the form to include an email field ' +
                'as it is required for setting up a recurring ' +
                'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None,
                                request.FILES or None)
    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated():
            billing_form.initial = {
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email
            }
    else:
        billing_form = None

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form
                                         or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase +
                                                  string.ascii_uppercase)

                    user_list = User.objects.filter(
                        email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30],
                                                 email=emailfield,
                                                 first_name=firstnamefield,
                                                 last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator,
                                                    owner=anonymous_creator,
                                                    creator=anonymous_creator,
                                                    phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To': form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(
                entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(
                    email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from  # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To': email_from})
            email_copies = [
                e.strip() for e in form.email_copies.split(',') if e.strip()
            ]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append(
                                    (f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment
                    or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get(
                    'custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(
                            1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                        user=rp_user,
                        description=form.title,
                        billing_period=entry.pricing.billing_period,
                        billing_start_dt=billing_start_dt,
                        num_days=entry.pricing.num_days,
                        due_sore=entry.pricing.due_sore,
                        payment_amount=price,
                        taxable=entry.pricing.taxable,
                        tax_rate=entry.pricing.tax_rate,
                        has_trial_period=entry.pricing.has_trial_period,
                        trial_period_start_dt=trial_period_start_dt,
                        trial_period_end_dt=trial_period_end_dt,
                        trial_amount=entry.pricing.trial_amount,
                        creator=rp_user,
                        creator_username=rp_user.username,
                        owner=rp_user,
                        owner_username=rp_user.username,
                    )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS,
                                         _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id,
                                    rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if (entry.payment_method.machine_name
                        ).lower() == 'credit-card':
                        return redirect('payment.pay_online', invoice.id,
                                        invoice.guid)
                    # redirect to invoice page
                    return redirect('invoice.view', invoice.id, invoice.guid)

            # default redirect
            form.completion_url = form.completion_url.strip(' ')
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 13
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.apps.emails.models import Email

    group = get_object_or_404(Group, slug=group_slug)
    if group.membership_types.all().exists():
        membership_type = group.membership_types.all()[0]
    else:
        membership_type = None
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(group=group,
                                             status=True,
                                             status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
                       request=request,
                       num_members=num_members)

    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = email.CONTENT_TYPE_HTML
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            email.send()

            messages.add_message(request, messages.SUCCESS,
                                 _('Successfully sent test email to yourself'))

            EventLog.objects.log(instance=email)

        else:
            # send email to members
            for member in members:
                original_body = email.body
                email.recipient = member.member.email
                if membership_type:
                    [membership] = member.member.membershipdefault_set.exclude(
                        status_detail='archive').order_by(
                            '-create_dt')[:1] or [None]
                    if membership:
                        # do find and replace
                        urls_dict = membership.get_common_urls()
                        for key in urls_dict.keys():
                            email.body = email.body.replace(
                                '[%s]' % key, urls_dict[key])
                email.send()
                # restore back to the original
                email.body = original_body

            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully sent email to all %(num)s members in this group'
                  % {'num': num_members}))

            EventLog.objects.log(instance=email)

        return redirect('group.detail', group_slug=group_slug)

    else:
        print('form errors', list(form.errors.items()))

    if membership_type:
        available_tokens = '[membership_link], [membership_type], [directory_url], [directory_edit_url], [invoice_link]'
    else:
        available_tokens = ''

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={
                              'group': group,
                              'num_members': num_members,
                              'membership_type': membership_type,
                              'available_tokens': available_tokens,
                              'form': form
                          })
Ejemplo n.º 14
0
def message(request, group_slug, template_name='user_groups/message.html'):
    """
    Send a message to the group
    """
    from tendenci.apps.emails.models import Email
    from django.core.mail import send_mail
    from django.core.mail import EmailMessage

    group = get_object_or_404(Group, slug=group_slug)
    EventLog.objects.log(instance=group)

    members = GroupMembership.objects.filter(group=group,
                                             status=True,
                                             status_detail='active')

    num_members = members.count()

    form = MessageForm(request.POST or None,
                       request=request,
                       num_members=num_members)

    if request.method == 'POST' and form.is_valid():

        email = Email()
        email.sender_display = request.user.get_full_name()
        email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        email.reply_to = email.sender
        email.content_type = email.CONTENT_TYPE_HTML
        email.subject = form.cleaned_data['subject']
        email.body = form.cleaned_data['body']
        email.save(request.user)

        # send email to myself (testing email)
        if form.cleaned_data['is_test']:
            email.recipient = request.user.email
            print(email.recipient)
            email.send()

            messages.add_message(request, messages.SUCCESS,
                                 _('Successfully sent test email to yourself'))

            EventLog.objects.log(instance=email)

        else:
            #api_url = settings.MAILCHIMP_API_URL + '/campaigns/'
            #api_key = settings.MAILCHIMP_API_KEY
            #headers = {'Content-Type': 'application/json', 'Authorization': api_key}
            #response = requests.get(api_url, headers=headers);
            #jsonInput = json.loads(response.text);
            #list_results = [[x['id'], x['name']] for x in jsonInput['lists']]
            # print(list_results)
            #body_content = {"plain_text": "Hi There,\r\nThis is a test again.\r\n-Blake B\n==============================================\n\n"}
            msg = EmailMessage('Request Callback',
                               'Here is the message.',
                               to=['*****@*****.**'])
            msg.send()

            #send email to members
            for member in members:
                email.recipient = member.member.email
                print(email.recipient)
                #try:
                #test = send_mail(
                #    'Subject here',
                #    'Here is the message.',
                #    ['*****@*****.**'],
                #    fail_silently=False,
                #)
                #print(test)
                #except SMTPException as e:
                #print('%s (%s)' % (e.message, type(e)))
                #email.send()

            messages.add_message(
                request, messages.SUCCESS,
                _('Successfully sent email to all %(num)s members in this group'
                  % {'num': num_members}))

            EventLog.objects.log(instance=email)

        return redirect('group.detail', group_slug=group_slug)

    else:
        print('form errors', form.errors.items())

    return render(request, template_name, {
        'group': group,
        'num_members': num_members,
        'form': form
    })
Ejemplo n.º 15
0
    def handle(self, *args, **options):
        from tendenci.apps.events.models import Event, Registrant, Organizer
        from tendenci.apps.emails.models import Email
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import convert_absolute_urls
        from tendenci.apps.events.utils import (render_event_email,
                                                get_default_reminder_template)

        verbosity = options['verbosity']
        site_url = get_setting('site', 'global', 'siteurl')
        now = datetime.now()
        today_tuple = (datetime(now.year, now.month, now.day, 0, 0, 0),
                       datetime(now.year, now.month, now.day, 23, 59, 59))

        # get a list of upcoming events that are specified to send reminders.
        events = Event.objects.filter(
            start_dt__gt=now,
            registration_configuration__enabled=True,
            registration_configuration__send_reminder=True,
            status=True,
            status_detail='active')
        events_list = []

        if events:
            for event in events:
                reg_conf = event.registration_configuration
                reminder_days = reg_conf.reminder_days
                if not reminder_days:
                    reminder_days = '1'
                days_list = reminder_days.split(',')

                for day in days_list:
                    try:
                        day = int(day)
                    except:
                        continue

                    start_dt = event.start_dt - timedelta(days=day)

                    if today_tuple[0] <= start_dt and start_dt <= today_tuple[
                            1]:
                        events_list.append(event)

            for event in events_list:
                registrants = Registrant.objects.filter(
                    reminder=True, registration__event=event, cancel_dt=None)

                reg_conf = event.registration_configuration
                [organizer
                 ] = Organizer.objects.filter(event=event)[:1] or [None]
                event.organizer = organizer

                email = reg_conf.email
                if not email:
                    email = Email()

                if not email.sender_display:
                    if organizer.name:
                        email.sender_display = organizer.name

                if not email.reply_to:
                    if organizer.user and organizer.user.email:
                        email.reply_to = organizer.user.email

                if not email.subject:
                    email.subject = 'Reminder: %s' % event.title
                else:
                    email.subject = 'Reminder: %s' % email.subject

                if not email.body:
                    email.body = get_default_reminder_template(event)

                email = render_event_email(event, email)

                # replace the relative links with absolute urls
                # in the email body and subject
                email.body = convert_absolute_urls(email.body, site_url)

                event.email = email
                self.send_reminders(event, registrants, verbosity=verbosity)
Ejemplo n.º 16
0
    def handle(self, *args, **options):
        from tendenci.apps.events.models import Event, Registrant, Organizer
        from tendenci.apps.emails.models import Email
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import convert_absolute_urls
        from tendenci.apps.events.utils import (render_event_email,
                                  get_default_reminder_template)

        verbosity = options['verbosity']
        site_url = get_setting('site', 'global', 'siteurl')
        now = datetime.now()
        today_tuple = (datetime(now.year, now.month, now.day, 0, 0, 0),
                       datetime(now.year, now.month, now.day, 23, 59, 59))

        # get a list of upcoming events that are specified to send reminders.
        events = Event.objects.filter(start_dt__gt=now,
                                registration_configuration__enabled=True,
                                registration_configuration__send_reminder=True,
                                status=True,
                                status_detail='active')
        events_list = []

        if events:
            for event in events:
                reg_conf = event.registration_configuration
                reminder_days = reg_conf.reminder_days
                if not reminder_days:
                    reminder_days = '1'
                days_list = reminder_days.split(',')

                for day in days_list:
                    try:
                        day = int(day)
                    except:
                        continue

                    start_dt = event.start_dt - timedelta(days=day)

                    if today_tuple[0] <= start_dt and start_dt <= today_tuple[1]:
                        events_list.append(event)

            for event in events_list:
                registrants = Registrant.objects.filter(
                                reminder=True,
                                registration__event=event,
                                cancel_dt=None
                                )

                reg_conf = event.registration_configuration
                [organizer] = Organizer.objects.filter(event=event)[:1] or [None]
                event.organizer = organizer

                email = reg_conf.email
                if not email:
                    email = Email()

                if not email.sender_display:
                    if organizer.name:
                        email.sender_display = organizer.name

                if not email.reply_to:
                    if organizer.user and organizer.user.email:
                        email.reply_to = organizer.user.email

                if not email.subject:
                    email.subject = 'Reminder: %s' % event.title
                else:
                    email.subject = 'Reminder: %s' % email.subject

                if not email.body:
                    email.body = get_default_reminder_template(event)

                email = render_event_email(event, email)

                # replace the relative links with absolute urls
                # in the email body and subject
                email.body = convert_absolute_urls(email.body, site_url)

                event.email = email
                self.send_reminders(event, registrants, verbosity=verbosity)