예제 #1
0
파일: views.py 프로젝트: bboud88/tendenci-1
def email_invoice(request,
                  invoice_id,
                  form_class=EmailInvoiceForm,
                  template_name='invoices/email_invoice.html'):
    if not request.user.profile.is_superuser:
        raise Http403

    invoice = get_object_or_404(Invoice, pk=invoice_id)

    if request.method == "POST":
        email = Email()
        form = form_class(request.POST, instance=email)

        if form.is_valid():
            email = form.save(commit=False)
            email.sender_display = request.user.get_full_name()
            email.reply_to = request.user.email
            email.recipient = form.cleaned_data['recipient']
            email.content_type = "html"
            email.recipient_cc = form.cleaned_data['cc']

            attachment = form.cleaned_data['attachment']
            kwargs = {}
            if attachment:
                result = invoice_pdf(request, invoice)
                kwargs['attachments'] = [("invoice_{}.pdf".format(invoice.id),
                                          result.getvalue(), 'application/pdf')
                                         ]
            email.send(**kwargs)

            EventLog.objects.log(instance=email)
            msg_string = 'Successfully sent email invoice to {}.'.format(
                email.recipient)
            messages.add_message(request, messages.SUCCESS, msg_string)

            return HttpResponseRedirect(
                reverse('invoice.view', args=([invoice_id])))

    else:
        template = get_template("invoices/email_invoice_template.html")
        body_initial = template.render(context={'invoice': invoice},
                                       request=request)
        form = form_class(
            initial={
                'subject': 'Invoice for {}'.format(invoice.title),
                'recipient': invoice.bill_to_email,
                'body': body_initial
            })

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={
                              'invoice': invoice,
                              'form': form
                          })
예제 #2
0
    def __init__(self):
        self.site_display_name = get_setting('site', 'global', 'sitedisplayname')
        self.site_contact_name = get_setting('site', 'global', 'sitecontactname')
        self.site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        self.reply_to_email = get_setting('module', 'payments', 'paymentrecipients')
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting('site', 'global', 'siteurl')

        self.email = Email()
        self.email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email

        self.admin_emails = self.get_admin_emails()
예제 #3
0
파일: utils.py 프로젝트: PaulSD/tendenci
def profile_edit_admin_notify(request, old_user, old_profile, profile, **kwargs):

    subject = 'User Account Modification Notice for %s' % get_setting('site', 'global', 'sitedisplayname')
    body = render_to_string(template_name='profiles/edit_notice.txt',
                               context={'old_user':old_user,
                                'old_profile': old_profile,
                                'profile': profile},
                               request=request)

    sender = settings.DEFAULT_FROM_EMAIL
    recipients = ['%s<%s>' % (r[0], r[1]) for r in settings.ADMINS]
    email = Email(
            sender=sender,
            recipient=recipients,
            subject=subject,
            body=body)
    email.send(fail_silently=True)
예제 #4
0
    def save(
            self,
            email_template_name='registration/password_reset_email_user_list.html',
            **kwargs):
        """
        Generates a one-use only link for resetting password and sends to the designated email.
        The email will contain links for resetting passwords for all accounts associated to the email.
        """
        from django.core.mail import send_mail

        email_template_name = 'registration/password_reset_email_user_list.html'

        domain_override = kwargs.get('domain_override', False)
        use_https = kwargs.get('use_https', False)
        token_generator = kwargs.get('token_generator',
                                     default_token_generator)

        user_list = []
        for user in self.users_cache:
            user_list.append({
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
            })
        if not domain_override:
            site_name = get_setting('site', 'global', 'sitedisplayname')
        else:
            site_name = domain_override
        site_url = get_setting('site', 'global', 'siteurl')
        t = loader.get_template(email_template_name)
        c = {
            'email': self.email,
            'site_url': site_url,
            'site_name': site_name,
            'user_list': user_list,
            'protocol': use_https and 'https' or 'http',
        }

        from_email = get_setting(
            'site', 'global',
            'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        email = Email(sender=from_email,
                      recipient=user.email,
                      subject=_("Password reset on %s") % site_name,
                      body=t.render(Context(c)))
        email.send()
예제 #5
0
파일: utils.py 프로젝트: goetzk/tendenci
def profile_edit_admin_notify(request, old_user, old_profile, profile, **kwargs):
    from django.template import RequestContext

    subject = 'User Account Modification Notice for %s' % get_setting('site', 'global', 'sitedisplayname')
    body = render_to_string('profiles/edit_notice.txt',
                               {'old_user':old_user,
                                'old_profile': old_profile,
                                'profile': profile},
                               context_instance=RequestContext(request))

    sender = settings.DEFAULT_FROM_EMAIL
    recipients = ['%s<%s>' % (r[0], r[1]) for r in settings.ADMINS]
    email = Email(
            sender=sender,
            recipient=recipients,
            subject=subject,
            body=body)
    email.send(fail_silently=True)
        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()
예제 #7
0
def make_payment_email_user(request, make_payment, invoice, **kwargs):
    from django.core.mail.message import EmailMessage
    from django.template.loader import render_to_string
    from django.conf import settings
    from django.template import RequestContext

    subject = render_to_string('make_payments/email_user_subject.txt',
                               {'make_payment':make_payment},
                               context_instance=RequestContext(request))
    body = render_to_string('make_payments/email_user.txt', {'make_payment':make_payment,
                                                             'invoice':invoice},
                                                             context_instance=RequestContext(request))
    sender = settings.DEFAULT_FROM_EMAIL
    recipient = make_payment.email
    email = Email(
            sender=sender,
            recipient=recipient,
            subject=subject,
            body=body)
    email.send(fail_silently=True)
예제 #8
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()
예제 #9
0
파일: forms.py 프로젝트: tendenci/tendenci
    def save(self, email_template_name='registration/password_reset_email_user_list.html', **kwargs):
        """
        Generates a one-use only link for resetting password and sends to the designated email.
        The email will contain links for resetting passwords for all accounts associated to the email.
        """
        email_template_name = 'registration/password_reset_email_user_list.html'

        domain_override = kwargs.get('domain_override', False)
        use_https = kwargs.get('use_https', False)
        token_generator = kwargs.get('token_generator', default_token_generator)

        user_list = []
        for user in self.users_cache:
            user_list.append({
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'user': user,
                    'token': token_generator.make_token(user),
                })
        if not domain_override:
            site_name = get_setting('site', 'global', 'sitedisplayname')
        else:
            site_name = domain_override
        site_url = get_setting('site', 'global', 'siteurl')
        t = loader.get_template(email_template_name)
        c = {
            'email': self.email,
            'site_url': site_url,
            'site_name': site_name,
            'user_list': user_list,
            'protocol': use_https and 'https' or 'http',
        }

        from_email = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        email = Email(
                sender=from_email,
                recipient=user.email,
                subject=_("Password reset on %s") % site_name,
                body=t.render(context=c))
        email.send()
예제 #10
0
def make_payment_email_user(request, make_payment, invoice, **kwargs):
    from django.template.loader import render_to_string
    from django.conf import settings

    subject = render_to_string(
        template_name='make_payments/email_user_subject.txt',
        context={'make_payment': make_payment},
        request=request)
    subject = subject.replace('\n', ' ')
    body = render_to_string(template_name='make_payments/email_user.txt',
                            context={
                                'make_payment': make_payment,
                                'invoice': invoice
                            },
                            request=request)
    sender = settings.DEFAULT_FROM_EMAIL
    recipient = make_payment.email
    email = Email(sender=sender,
                  recipient=recipient,
                  subject=subject,
                  body=body)
    email.send(fail_silently=True)
    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()
예제 #12
0
파일: utils.py 프로젝트: ZHW123/tendenci
    def __init__(self):
        self.site_display_name = get_setting("site", "global", "sitedisplayname")
        self.site_contact_name = get_setting("site", "global", "sitecontactname")
        self.site_contact_email = get_setting("site", "global", "sitecontactemail")
        self.reply_to_email = get_setting("module", "payments", "paymentrecipients")
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting("site", "global", "siteurl")

        self.email = Email()
        self.email.sender = get_setting("site", "global", "siteemailnoreplyaddress")
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email

        self.admin_emails = self.get_admin_emails()
예제 #13
0
파일: views.py 프로젝트: goetzk/tendenci
def email_invoice(request, invoice_id, form_class=EmailInvoiceForm,
                  template_name='invoices/email_invoice.html'):
    if not request.user.profile.is_superuser:
        raise Http403

    invoice = get_object_or_404(Invoice, pk=invoice_id)

    if request.method == "POST":
        email = Email()
        form = form_class(request.POST, instance=email)

        if form.is_valid():
            email = form.save(commit=False)
            email.sender_display = request.user.get_full_name()
            email.reply_to = request.user.email
            email.recipient = form.cleaned_data['recipient']
            email.content_type = "html"
            email.recipient_cc = form.cleaned_data['cc']

            attachment = form.cleaned_data['attachment']
            kwargs = {}
            if attachment:
                result = invoice_pdf(request, invoice)
                kwargs['attachments'] = [("invoice_{}.pdf".format(invoice.id),
                                      result.getvalue(),
                                      'application/pdf')]
            email.send(**kwargs)

            EventLog.objects.log(instance=email)
            msg_string = 'Successfully sent email invoice to {}.'.format(email.recipient)
            messages.add_message(request, messages.SUCCESS, msg_string)

            return HttpResponseRedirect(reverse('invoice.view', args=([invoice_id])))

    else:
        template = get_template("invoices/email_invoice_template.html")
        body_initial  = template.render(RequestContext(request, {
                                       'invoice': invoice,}))
        form = form_class(initial={'subject': 'Invoice for {}'.format(invoice.title),
                                   'recipient': invoice.bill_to_email,
                                   'body': body_initial})

    return render_to_response(template_name, {
        'invoice': invoice,
        'form': form
        },context_instance=RequestContext(request))
예제 #14
0
파일: utils.py 프로젝트: goetzk/tendenci
    def __init__(self):
        self.site_display_name = get_setting('site', 'global', 'sitedisplayname')
        self.site_contact_name = get_setting('site', 'global', 'sitecontactname')
        self.site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        self.reply_to_email = get_setting('module', 'payments', 'paymentrecipients')
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting('site', 'global', 'siteurl')

        self.email = Email()
        self.email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email
        self.email_footer = render_to_string("email_footer.html")

        self.admin_emails = self.get_admin_emails()
예제 #15
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()
예제 #16
0
    def handle(self, *args, **options):
        import datetime
        import uuid
        from django.core.management import call_command
        from django.contrib.auth.models import User
        from tendenci.apps.emails.models import Email
        from tendenci.apps.explorer_extensions.models import DatabaseDumpFile, VALID_FORMAT_CHOICES

        dump_obj = None
        d_id = options.get('obj_id', None)
        if d_id:
            dump_obj = DatabaseDumpFile.objects.filter(pk=d_id)
            if dump_obj.exists():
                dump_obj = dump_obj[0]
            else:
                dump_obj = None

        if not dump_obj:
            dump_obj = DatabaseDumpFile()

        user_id = int(options['user_id'])

        if user_id == 0:
            msg = 'User ID is required. Usage: ./manage.py create_database_dump <user_id>'
            raise CommandError(msg)

        author = User.objects.filter(pk=user_id)
        if author.exists():
            author = author[0]
        else:
            author = None

        if not author:
            raise CommandError('Nonexistent user.')

        dump_obj.author = author

        fmt = options['export_format']

        if fmt not in VALID_FORMAT_CHOICES:
            raise CommandError('Format %s is not supported. Please use one of the following: %s' % (fmt, VALID_FORMAT_CHOICES))

        dump_obj.export_format = fmt
        dump_obj.save()

        print("Creating database dump...")

        content = ''
        dump_obj.dbfile.save(str(uuid.uuid4()), ContentFile(content))
        call_command('dumpdata', format=fmt, output=dump_obj.dbfile.path, exclude=['captcha.captchastore', 'files.multiplefile', 'events.standardregform', 'help_files', 'explorer_extensions'])

        dump_obj.status = "completed"
        dump_obj.end_dt = datetime.datetime.now() + datetime.timedelta(days=3)
        dump_obj.save()

        # File is created.
        # Send email to author
        context = { 'obj':dump_obj, 'author':dump_obj.author }
        email_subject = "Your database export (id:%d) is ready for download" % dump_obj.id
        email_body = render_to_string(template_name="explorer/dbdump_ready_email_body.html", context=context)
        email = Email(recipient=dump_obj.author.email, subject=email_subject, body=email_body)
        email.send()

        print("Done!")
예제 #17
0
def process_export(group_id, export_target='all', identifier=u'', user_id=0):
    """
    Process export for group members and/or group subscribers.
    """

    [group] = Group.objects.filter(id=group_id)[:1] or [None]
    if not group:
        return

    # pull 100 rows per query
    # be careful of the memory usage
    rows_per_batch = 100

    identifier = identifier or str(time.time())
    file_dir = 'export/groups/'

    file_path_temp = '%sgroup_%d_%s_%s_temp.csv' % (file_dir, group.id,
                                                    export_target, identifier)

    # labels
    user_fields = [
        'id', 'first_name', 'last_name', 'email', 'is_active', 'is_staff',
        'is_superuser'
    ]
    profile_fields = [
        'direct_mail', 'company', 'address', 'address2', 'city', 'state',
        'zipcode', 'country', 'phone', 'create_dt'
    ]
    labels = user_fields + profile_fields

    field_dict = OrderedDict([(label.lower().replace(" ", "_"), '')
                              for label in labels])

    with default_storage.open(file_path_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_dict.keys())

        # process regular group members
        count_members = group.members.filter(
            group_member__status=True,
            group_member__status_detail='active').count()
        num_rows_processed = 0
        while num_rows_processed < count_members:
            users = group.members.filter(
                group_member__status=True,
                group_member__status_detail='active').select_related(
                    'profile')[num_rows_processed:(num_rows_processed +
                                                   rows_per_batch)]
            num_rows_processed += rows_per_batch
            row_dict = field_dict.copy()
            for user in users:
                profile = user.profile
                for field_name in user_fields:
                    if hasattr(user, field_name):
                        row_dict[field_name] = getattr(user, field_name)
                for field_name in profile_fields:
                    if hasattr(profile, field_name):
                        row_dict[field_name] = getattr(profile, field_name)
                for k, v in row_dict.items():
                    if not isinstance(v, basestring):
                        if isinstance(v, datetime):
                            row_dict[k] = v.strftime('%Y-%m-%d %H:%M:%S')
                        elif isinstance(v, date):
                            row_dict[k] = v.strftime('%Y-%m-%d')
                        else:
                            row_dict[k] = smart_str(v)

                csv_writer.writerow(row_dict.values())

    # rename the file name
    file_path = '%sgroup_%d_%s_%s.csv' % (file_dir, group.id, export_target,
                                          identifier)
    default_storage.save(file_path, default_storage.open(file_path_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_path_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(id=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('group.members_export_download',
                               args=[group.slug, export_target, identifier])
        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'group': group,
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name
        }

        subject = render_to_string(
            'user_groups/exports/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string('user_groups/exports/export_ready_body.html',
                                parms)

        email = Email(recipient=user.email, subject=subject, body=body)

        email.send()
예제 #18
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)
예제 #19
0
    def send_newsletter(self, newsletter_id, **kwargs):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter, NewsletterRecurringData
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import validate_email

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print(
                'Exiting..Please set up your newsletter email provider before proceeding.'
            )
            return

        print("Started sending newsletter...")

        if newsletter_id == 0:
            raise CommandError(
                'Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>'
            )

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError(
                'You are trying to send a newsletter that does not exist.')

        # validate sender
        if not validate_email(newsletter.email.sender):
            raise CommandError(
                '"{}" is not a valid sender email address.'.format(
                    newsletter.email.sender))

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        if newsletter.schedule:
            # save start_dt and status for the recurring
            nr_data = NewsletterRecurringData(
                newsletter=newsletter,
                start_dt=datetime.datetime.now(),
                send_status=newsletter.send_status)
            nr_data.save()
            newsletter.nr_data = nr_data

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/",
                                        "href=\"%s/" % self.site_url)

        if newsletter.group and newsletter.group.membership_types.all().exists(
        ):
            membership_type = newsletter.group.membership_types.all()[0]
        else:
            membership_type = None

        counter = 0
        for recipient in recipients:
            if hasattr(recipient.member, 'profile'):
                profile = recipient.member.profile
            else:
                profile = None

            # Skip if Don't Send Email is on
            if newsletter.enforce_direct_mail_flag:
                if profile and not profile.direct_mail:
                    continue

            # skip if not a valid email address
            if not validate_email(recipient.member.email):
                continue

            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]',
                                          recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]',
                                          recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                #body = body.replace('[unsubscribe_url]', recipient.noninteractive_unsubscribe_url)
                # The unsubscribe_url link should be something like <a href="[unsubscribe_url]">Unsubscribe</a>.
                # But it can be messed up sometimes. Let's prevent that from happening.
                p = r'(href=\")([^\"]*)(\[unsubscribe_url\])(\")'
                body = re.sub(
                    p,
                    r'\1' + recipient.noninteractive_unsubscribe_url + r'\4',
                    body)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]',
                                    newsletter.get_browser_view_url())

            if membership_type:
                [membership] = recipient.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():
                        body = body.replace('[%s]' % key, urls_dict[key])

            email_to_send = Email(subject=subject,
                                  body=body,
                                  sender=email.sender,
                                  sender_display=email.sender_display,
                                  reply_to=email.reply_to,
                                  recipient=recipient.member.email)
            print(u"Sending to {}".format(str(recipient.member.email)))
            email_to_send.send(connection=connection)
            counter += 1
            print(u"Newsletter sent to {}".format(str(recipient.member.email)))

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and validate_email(recipient.member.profile.email2):
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print(u"Newsletter sent to {}".format(
                    str(recipient.member.profile.email2)))

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()
        if newsletter.nr_data:
            # save the finish_dt and email_sent_count for the recurring
            newsletter.nr_data.finish_dt = datetime.datetime.now()
            newsletter.nr_data.email_sent_count = newsletter.email_sent_count
            newsletter.nr_data.send_status = newsletter.send_status
            newsletter.nr_data.save()

        print("Successfully sent %s newsletter emails." % counter)

        print("Sending confirmation message to creator...")
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global',
                                 'siteurl') + newsletter.get_absolute_url()
        params = {
            'first_name': newsletter.email.creator.first_name,
            'subject': newsletter.email.subject,
            'count': counter,
            'detail_url': detail_url
        }

        body = render_to_string(
            template_name='newsletters/newsletter_sent_email_body.html',
            context=params)

        email = Email(recipient=newsletter.email.sender,
                      subject=subject,
                      body=body)

        email.send(connection=connection)

        print("Confirmation email sent.")

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print('Cache cleared!')
예제 #20
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})
예제 #21
0
    def send_newsletter(self, newsletter_id, **kwargs):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter
        from tendenci.apps.site_settings.utils import get_setting

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print(
                'Exiting..Please set up your newsletter email provider before proceeding.'
            )
            return

        print "Started sending newsletter..."

        if newsletter_id == 0:
            raise CommandError(
                'Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>'
            )

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError(
                'You are trying to send a newsletter that does not exist.')

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/",
                                        "href=\"%s/" % self.site_url)

        counter = 0
        for recipient in recipients:
            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]',
                                          recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]',
                                          recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                body = body.replace('[unsubscribe_url]',
                                    recipient.noninteractive_unsubscribe_url)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]',
                                    newsletter.get_browser_view_url())

            email_to_send = Email(subject=subject,
                                  body=body,
                                  sender=email.sender,
                                  sender_display=email.sender_display,
                                  reply_to=email.reply_to,
                                  recipient=recipient.member.email)
            email_to_send.send(connection=connection)
            counter += 1
            print "Newsletter sent to %s" % recipient.member.email

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and recipient.member.profile.email2:
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print "Newsletter sent to %s" % recipient.member.profile.email2

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()

        print "Successfully sent %s newsletter emails." % counter

        print "Sending confirmation message to creator..."
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global',
                                 'siteurl') + newsletter.get_absolute_url()
        params = {
            'first_name': newsletter.email.creator.first_name,
            'subject': newsletter.email.subject,
            'count': counter,
            'detail_url': detail_url
        }

        body = render_to_string('newsletters/newsletter_sent_email_body.html',
                                params)

        email = Email(recipient=newsletter.email.sender,
                      subject=subject,
                      body=body)

        email.send(connection=connection)

        print "Confirmation email sent."

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print 'Cache cleared!'
    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)
예제 #23
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            unicode(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            # test for request in the extra_context
            if 'request' in extra_context.keys():
                context = RequestContext(extra_context['request'])
                extra_context.update({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)
            else:
                # update context with user specific translations
                context = Context({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, context)

            # Strip newlines from subject
            subject = ''.join(render_to_string('notification/email_subject.txt', {
                'message': messages['short'][0],
            }, context).splitlines())

            body = render_to_string('notification/email_body.txt', {
                'message': messages['full'][0],
            }, context)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)
예제 #24
0
class RecurringPaymentEmailNotices(object):
    def __init__(self):
        self.site_display_name = get_setting('site', 'global', 'sitedisplayname')
        self.site_contact_name = get_setting('site', 'global', 'sitecontactname')
        self.site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        self.reply_to_email = get_setting('module', 'payments', 'paymentrecipients')
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting('site', 'global', 'siteurl')

        self.email = Email()
        self.email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email

        self.admin_emails = self.get_admin_emails()

    def get_admin_emails(self):
        payment_admins = get_setting('module', 'payments', 'paymentrecipients')
        if payment_admins:
            payment_admins = payment_admins.split(',')
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting('site', 'global', 'admincontactemail')).split(',')

        if admin_emails:
            admin_emails = ','.join(admin_emails)

        return admin_emails

    def get_script_support_emails(self):
        admins = getattr(settings, 'ADMINS', None)
        if admins:
            recipients_list = [admin[1] for admin in admins]
            return ','.join(recipients_list)

        return None

    def email_script_support_transaction_error(self, payment_transaction):
        """if there is an error other than transaction not being approved, notify us.
        """
        self.email.recipient = self.get_script_support_emails()
        if self.email.recipient:
            template_name = "recurring_payments/email_script_support_transaction.html"
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.priority = 1
                self.email.subject = _('Recurring payment transaction error on %(dname)s' % {
                                                                            'dname':self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_transaction_result(self, payment_transaction, success=True):
        """Send admins the result after the transaction is processed.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_transaction.html"
            user_in_texas = False
            if payment_transaction.payment.state:
                if payment_transaction.payment.state.lower() in ['texas', 'tx']:
                    user_in_texas = True
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url,
                                                'user_in_texas': user_in_texas
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                if not success:
                    self.email.subject = _('Recurring payment transaction failed on %(dname)s' % {
                                                                            'dname': self.site_display_name})
                    self.email.priority = 1
                else:
                    self.email.subject = _('Recurring payment transaction processed on %(dname)s' % {
                                                                                'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_transaction_result(self, payment_transaction):
        """Send customer an email after the transaction is processed.
        """
        self.email.recipient = payment_transaction.recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_transaction.html"
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                if payment_transaction.status:
                    self.email.subject = _('Payment received ')
                else:
                    self.email.subject = _('Payment failed ')
                self.email.subject = _("%(subj)s for %(desc)s " % {
                            'subj': self.email.subject,
                            'desc': payment_transaction.recurring_payment.description})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_no_payment_profile(self, recurring_payment):
        """Notify admin that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_no_payment_profile.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _('Payment method not setup for %(rp)s on %(dname)s' % {
                                    'rp': recurring_payment ,
                                    'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_no_payment_profile(self, recurring_payment):
        """Notify customer that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_no_payment_profile.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _('Please update your payment method for %(rp)s on %(dname)s' % {
                                    'rp': recurring_payment.description,
                                    'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_account_disabled(self, recurring_payment, user_by):
        """Notify admin that the recurring payment account is disabled.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_account_disabled.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'user_by': user_by,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _('Recurring Payment Account (ID:%(id)d) Disabled by %(usr)s on %(dname)s' % {
                       'id':recurring_payment.id,
                       'usr' : user_by,
                       'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass
예제 #25
0
파일: forms.py 프로젝트: BIGGANI/tendenci
    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
예제 #26
0
파일: utils.py 프로젝트: BIGGANI/tendenci
def process_export(export_fields='all_fields', export_status_detail='',
                   identifier=u'', user_id=0):
    from tendenci.apps.perms.models import TendenciBaseModel

    if export_fields == 'main_fields':
        field_list = [
            'headline',
            'slug',
            'summary',
            'body',
            'source',
            'first_name',
            'last_name',
            'address',
            'address2',
            'city',
            'state',
            'zip_code',
            'country',
            'phone',
            'phone2',
            'fax',
            'email',
            'email2',
            'website',
            'list_type',
            'requested_duration',
            'activation_dt',
            'expiration_dt',
            'tags',
            'enclosure_url',
            'enclosure_type',
            'enclosure_length',
            'status',
            'status_detail']
    else:
        # base ------------
        base_field_list = [
            smart_str(field.name) for field in TendenciBaseModel._meta.fields
            if not field.__class__ == AutoField]

        field_list = [
            smart_str(field.name) for field in Directory._meta.fields
            if not field.__class__ == AutoField]
        field_list = [
            name for name in field_list
            if not name in base_field_list]
        field_list.remove('guid')
        # append base fields at the end
        field_list = field_list + base_field_list

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/directories/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        directories = Directory.objects.all()
        if export_status_detail:
            directories = directories.filter(status_detail__icontains=export_status_detail)
        for directory in directories:
            items_list = []
            for field_name in field_list:
                item = getattr(directory, field_name)
                if item is None:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                    elif field_name == 'invoice':
                        # display total vs balance
                        item = 'Total: %d / Balance: %d' % (item.total, item.balance)
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/directories/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('directory.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'export_status_detail': export_status_detail,
            'export_fields': export_fields}

        subject = render_to_string(
            'directories/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string(
            'directories/notices/export_ready_body.html', parms)

        email = Email(
            recipient=user.email,
            subject=subject,
            body=body)
        email.send()
예제 #27
0
파일: utils.py 프로젝트: ZHW123/tendenci
class RecurringPaymentEmailNotices(object):
    def __init__(self):
        self.site_display_name = get_setting("site", "global", "sitedisplayname")
        self.site_contact_name = get_setting("site", "global", "sitecontactname")
        self.site_contact_email = get_setting("site", "global", "sitecontactemail")
        self.reply_to_email = get_setting("module", "payments", "paymentrecipients")
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting("site", "global", "siteurl")

        self.email = Email()
        self.email.sender = get_setting("site", "global", "siteemailnoreplyaddress")
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email

        self.admin_emails = self.get_admin_emails()

    def get_admin_emails(self):
        payment_admins = get_setting("module", "payments", "paymentrecipients")
        if payment_admins:
            payment_admins = payment_admins.split(",")
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting("site", "global", "admincontactemail")).split(",")

        if admin_emails:
            admin_emails = ",".join(admin_emails)

        return admin_emails

    def get_script_support_emails(self):
        admins = getattr(settings, "ADMINS", None)
        if admins:
            recipients_list = [admin[1] for admin in admins]
            return ",".join(recipients_list)

        return None

    def email_script_support_transaction_error(self, payment_transaction):
        """if there is an error other than transaction not being approved, notify us.
        """
        self.email.recipient = self.get_script_support_emails()
        if self.email.recipient:
            template_name = "recurring_payments/email_script_support_transaction.html"
            try:
                email_content = render_to_string(
                    template_name,
                    {"pt": payment_transaction, "site_display_name": self.site_display_name, "site_url": self.site_url},
                )
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.priority = 1
                self.email.subject = _(
                    "Recurring payment transaction error on %(dname)s" % {"dname": self.site_display_name}
                )

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_transaction_result(self, payment_transaction, success=True):
        """Send admins the result after the transaction is processed.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_transaction.html"
            user_in_texas = False
            if payment_transaction.payment.state:
                if payment_transaction.payment.state.lower() in ["texas", "tx"]:
                    user_in_texas = True
            try:
                email_content = render_to_string(
                    template_name,
                    {
                        "pt": payment_transaction,
                        "site_display_name": self.site_display_name,
                        "site_url": self.site_url,
                        "user_in_texas": user_in_texas,
                    },
                )
                self.email.body = email_content
                self.email.content_type = "html"
                if not success:
                    self.email.subject = _(
                        "Recurring payment transaction failed on %(dname)s" % {"dname": self.site_display_name}
                    )
                    self.email.priority = 1
                else:
                    self.email.subject = _(
                        "Recurring payment transaction processed on %(dname)s" % {"dname": self.site_display_name}
                    )

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_transaction_result(self, payment_transaction):
        """Send customer an email after the transaction is processed.
        """
        self.email.recipient = payment_transaction.recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_transaction.html"
            try:
                email_content = render_to_string(
                    template_name,
                    {"pt": payment_transaction, "site_display_name": self.site_display_name, "site_url": self.site_url},
                )
                self.email.body = email_content
                self.email.content_type = "html"
                if payment_transaction.status:
                    self.email.subject = _("Payment received ")
                else:
                    self.email.subject = _("Payment failed ")
                self.email.subject = _(
                    "%(subj)s for %(desc)s "
                    % {"subj": self.email.subject, "desc": payment_transaction.recurring_payment.description}
                )

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_no_payment_profile(self, recurring_payment):
        """Notify admin that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_no_payment_profile.html"
            try:
                email_content = render_to_string(
                    template_name,
                    {"rp": recurring_payment, "site_display_name": self.site_display_name, "site_url": self.site_url},
                )
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _(
                    "Payment method not setup for %(rp)s on %(dname)s"
                    % {"rp": recurring_payment, "dname": self.site_display_name}
                )

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_no_payment_profile(self, recurring_payment):
        """Notify customer that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_no_payment_profile.html"
            try:
                email_content = render_to_string(
                    template_name,
                    {"rp": recurring_payment, "site_display_name": self.site_display_name, "site_url": self.site_url},
                )
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _(
                    "Please update your payment method for %(rp)s on %(dname)s"
                    % {"rp": recurring_payment.description, "dname": self.site_display_name}
                )

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_account_disabled(self, recurring_payment, user_by):
        """Notify admin that the recurring payment account is disabled.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_account_disabled.html"
            try:
                email_content = render_to_string(
                    template_name,
                    {
                        "rp": recurring_payment,
                        "user_by": user_by,
                        "site_display_name": self.site_display_name,
                        "site_url": self.site_url,
                    },
                )
                self.email.body = email_content
                self.email.content_type = "html"
                self.email.subject = _(
                    "Recurring Payment Account (ID:%(id)d) Disabled by %(usr)s on %(dname)s"
                    % {"id": recurring_payment.id, "usr": user_by, "dname": self.site_display_name}
                )

                self.email.send()
            except TemplateDoesNotExist:
                pass
예제 #28
0
파일: utils.py 프로젝트: ediaz1/tendenci
def process_export(export_fields='all_fields', identifier=u'', user_id=0):
    from tendenci.apps.perms.models import TendenciBaseModel

    if export_fields == 'main_fields':
        user_field_list = [
            'username',
            'first_name',
            'last_name',
            'email']

        profile_field_list = [
            'salutation',
            'initials',
            'display_name',
            'company',
            'department',
            'position_title',
            'sex',
            'address',
            'address2',
            'city',
            'state',
            'zipcode',
            'country',
            'phone',
            'phone2',
            'fax',
            'work_phone',
            'home_phone',
            'mobile_phone',
            'url',
            'url2',
            'dob',
            'status_detail']
    else:
        # base ------------
        base_field_list = [
            smart_str(field.name) for field in TendenciBaseModel._meta.fields
            if not field.__class__ == AutoField]

        # user ------------
        user_field_list = [
            smart_str(field.name) for field in User._meta.fields
            if not field.__class__ == AutoField]
        user_field_list.remove('password')

        # profile ---------
        profile_field_list = [
            smart_str(field.name) for field in Profile._meta.fields
            if not field.__class__ == AutoField]
        profile_field_list = [
            name for name in profile_field_list
            if not name in base_field_list]
        profile_field_list.remove('guid')
        profile_field_list.remove('user')
        # append base fields at the end

    field_list = user_field_list + profile_field_list

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/profiles/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        profiles = Profile.objects.all()
        for profile in profiles:
            p_user = profile.user
            items_list = []
            for field_name in field_list:
                if field_name in profile_field_list:
                    item = getattr(profile, field_name)
                elif field_name in user_field_list:
                    item = getattr(p_user, field_name)
                else:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/profiles/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('profile.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'export_fields': export_fields}

        subject = render_to_string(
            'profiles/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string(
            'profiles/notices/export_ready_body.html', parms)

        email = Email(
            recipient=user.email,
            subject=subject,
            body=body)
        email.send()
예제 #29
0
    def send_newsletter(self, newsletter_id, **kwargs):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import validate_email

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print('Exiting..Please set up your newsletter email provider before proceeding.')
            return

        print("Started sending newsletter...")

        if newsletter_id == 0:
            raise CommandError('Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>')

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError('You are trying to send a newsletter that does not exist.')

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/", "href=\"%s/" % self.site_url)

        counter = 0
        for recipient in recipients:
            # skip if not a valid email address
            if not validate_email(recipient.member.email):
                continue

            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]', recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]', recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                #body = body.replace('[unsubscribe_url]', recipient.noninteractive_unsubscribe_url)
                # The unsubscribe_url link should be something like <a href="[unsubscribe_url]">Unsubscribe</a>.
                # But it can be messed up sometimes. Let's prevent that from happening.
                p = r'(href=\")([^\"]*)(\[unsubscribe_url\])(\")'
                body = re.sub(p, r'\1' + recipient.noninteractive_unsubscribe_url + r'\4', body)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]', newsletter.get_browser_view_url())

            email_to_send = Email(
                    subject=subject,
                    body=body,
                    sender=email.sender,
                    sender_display=email.sender_display,
                    reply_to=email.reply_to,
                    recipient=recipient.member.email
                    )
            print(u"Sending to {}".format(unicode(recipient.member.email)))
            email_to_send.send(connection=connection)
            counter += 1
            print(u"Newsletter sent to {}".format(unicode(recipient.member.email)))

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and validate_email(recipient.member.profile.email2):
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print(u"Newsletter sent to {}".format(unicode(recipient.member.profile.email2)))

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()

        print("Successfully sent %s newsletter emails." % counter)

        print("Sending confirmation message to creator...")
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global', 'siteurl') + newsletter.get_absolute_url()
        params = {'first_name': newsletter.email.creator.first_name,
                    'subject': newsletter.email.subject,
                    'count': counter,
                    'detail_url': detail_url}

        body = render_to_string(
                'newsletters/newsletter_sent_email_body.html', params)

        email = Email(
            recipient=newsletter.email.sender,
            subject=subject,
            body=body)

        email.send(connection=connection)

        print("Confirmation email sent.")

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print('Cache cleared!')
예제 #30
0
    def handle(self, *args, **options):
        import datetime
        import uuid
        from StringIO import StringIO
        from django.core.management import call_command
        from django.core.files import File
        from django.contrib.auth.models import User
        from tendenci.apps.emails.models import Email
        from tendenci.apps.explorer_extensions.models import DatabaseDumpFile, VALID_FORMAT_CHOICES

        dump_obj = None
        d_id = options.get('obj_id', None)
        if d_id:
            dump_obj = DatabaseDumpFile.objects.filter(pk=d_id)
            if dump_obj.exists():
                dump_obj = dump_obj[0]
            else:
                dump_obj = None

        if not dump_obj:
            dump_obj = DatabaseDumpFile()

        user_id = int(options['user_id'])

        if user_id == 0:
            msg = 'User ID is required. Usage: ./manage.py create_database_dump <user_id>'
            raise CommandError(msg)

        author = User.objects.filter(pk=user_id)
        if author.exists():
            author = author[0]
        else:
            author = None

        if not author:
            raise CommandError('Nonexistent user.')

        dump_obj.author = author

        fmt = options['export_format']

        if fmt not in VALID_FORMAT_CHOICES:
            raise CommandError('Format %s is not supported. Please use one of the following: %s' % (fmt, VALID_FORMAT_CHOICES))

        dump_obj.export_format = fmt
        dump_obj.save()

        print("Creating database dump...")

        content = StringIO()
        call_command('dumpdata', format=fmt, stdout=content, exclude=['captcha.captchastore', 'files.multiplefile', 'events.standardregform', 'help_files', 'explorer_extensions'])

        dump_obj.dbfile.save(str(uuid.uuid1()), File(content))

        dump_obj.status = "completed"
        dump_obj.end_dt = datetime.datetime.now() + datetime.timedelta(days=3)
        dump_obj.save()

        # File is created.
        # Send email to author
        context = { 'obj':dump_obj, 'author':dump_obj.author }
        email_subject = "Your database export (id:%d) is ready for download" % dump_obj.id
        email_body = render_to_string("explorer/dbdump_ready_email_body.html", context)
        email = Email(recipient=dump_obj.author.email, subject=email_subject, body=email_body)
        email.send()

        print("Done!")
예제 #31
0
def process_export(identifier, user_id):
    field_list = [
        'guid',
        'slug',
        'timezone',
        'headline',
        'summary',
        'body',
        'source',
        'first_name',
        'last_name',
        'phone',
        'fax',
        'email',
        'website',
        'release_dt',
        'syndicate',
        'featured',
        'design_notes',
        'tags',
        'enclosure_url',
        'enclosure_type',
        'enclosure_length',
        'not_official_content',
        'entity',
    ]

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/articles/%s_temp.csv' % (identifier)

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        articles = Article.objects.filter(status_detail='active')

        for article in articles:
            items_list = []
            for field_name in field_list:
                item = getattr(article, field_name)

                if isinstance(item, datetime):
                    item = item.strftime('%Y-%m-%d %H:%M:%S')
                elif isinstance(item, date):
                    item = item.strftime('%Y-%m-%d')
                elif isinstance(item, time):
                    item = item.strftime('%H:%M:%S')
                elif isinstance(item, basestring):
                    item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/articles/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('article.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'date_today': datetime.now()
        }

        subject = render_to_string(
            'articles/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string('articles/notices/export_ready_body.html',
                                parms)

        email = Email(recipient=user.email, subject=subject, body=body)
        email.send()
예제 #32
0
def process_export(export_fields='all_fields', identifier=u'', user_id=0):
    from tendenci.apps.perms.models import TendenciBaseModel

    if export_fields == 'main_fields':
        user_field_list = ['username', 'first_name', 'last_name', 'email']

        profile_field_list = [
            'salutation', 'initials', 'display_name', 'company', 'department',
            'position_title', 'sex', 'address', 'address2', 'city', 'state',
            'zipcode', 'country', 'phone', 'phone2', 'fax', 'work_phone',
            'home_phone', 'mobile_phone', 'url', 'url2', 'dob', 'status_detail'
        ]
    else:
        # base ------------
        base_field_list = [
            smart_str(field.name) for field in TendenciBaseModel._meta.fields
            if not field.__class__ == AutoField
        ]

        # user ------------
        user_field_list = [
            smart_str(field.name) for field in User._meta.fields
            if not field.__class__ == AutoField
        ]
        user_field_list.remove('password')

        # profile ---------
        profile_field_list = [
            smart_str(field.name) for field in Profile._meta.fields
            if not field.__class__ == AutoField
        ]
        profile_field_list = [
            name for name in profile_field_list if name not in base_field_list
        ]
        profile_field_list.remove('guid')
        profile_field_list.remove('user')
        # append base fields at the end

    field_list = user_field_list + profile_field_list

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/profiles/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        profiles = Profile.objects.all()
        for profile in profiles:
            p_user = profile.user
            items_list = []
            for field_name in field_list:
                if field_name in profile_field_list:
                    item = getattr(profile, field_name)
                elif field_name in user_field_list:
                    item = getattr(p_user, field_name)
                else:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/profiles/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('profile.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'export_fields': export_fields
        }

        subject = render_to_string(
            'profiles/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string('profiles/notices/export_ready_body.html',
                                parms)

        email = Email(recipient=user.email, subject=subject, body=body)
        email.send()
예제 #33
0
파일: utils.py 프로젝트: goetzk/tendenci
def process_invoice_export(start_dt=None, end_dt=None,
                           identifier=u'', user_id=0):

    fields = ['id',
              'guid',
              'object_type',
              'object_id',
              'title',
              'tender_date',
              'bill_to',
              'bill_to_first_name',
              'bill_to_last_name',
              'bill_to_company',
              'bill_to_address',
              'bill_to_city',
              'bill_to_state',
              'bill_to_zip_code',
              'bill_to_country',
              'bill_to_phone',
              'bill_to_fax',
              'bill_to_email',
              'ship_to',
              'ship_to_first_name',
              'ship_to_last_name',
              'ship_to_company',
              'ship_to_address',
              'ship_to_city',
              'ship_to_state',
              'ship_to_zip_code',
              'ship_to_country',
              'ship_to_phone',
              'ship_to_fax',
              'ship_to_email',
              'ship_to_address_type',
              'receipt',
              'gift',
              'arrival_date_time',
              'greeting',
              'instructions',
              'po',
              'terms',
              'due_date',
              'ship_date',
              'ship_via',
              'fob',
              'project',
              'other',
              'message',
              'subtotal',
              'shipping',
              'shipping_surcharge',
              'box_and_packing',
              'tax_exempt',
              'tax_exemptid',
              'tax_rate',
              'taxable',
              'tax',
              'variance',
              'discount_amount',
              'total',
              'payments_credits',
              'balance',
              'disclaimer',
              'variance_notes',
              'admin_notes',
              'create_dt',
              'update_dt',
              'creator',
              'creator_username',
              'owner',
              'owner_username',
              'status_detail']

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/invoices/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(fields)

        invoices = Invoice.objects.filter(status=True,
                                          update_dt__gte=start_dt,
                                          update_dt__lte=end_dt)
        for invoice in invoices:
            items_list = []
            for field_name in fields:
                item = getattr(invoice, field_name)
                if item is None:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/invoices/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('invoice.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'start_dt': start_dt,
            'end_dt': end_dt}

        subject = render_to_string(
            'invoices/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string(
            'invoices/notices/export_ready_body.html', parms)

        email = Email(
            recipient=user.email,
            subject=subject,
            body=body)
        email.send()
예제 #34
0
    def handle(self, *args, **options):
        import datetime
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter
        from tendenci.apps.site_settings.utils import get_setting

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print('Exiting..Please set up your newsletter email provider before proceeding.')
            return


        print "Started sending newsletter..."

        newsletter_id = options['newsletter_id']
        if newsletter_id == 0:
            raise CommandError('Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>')

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError('You are trying to send a newsletter that does not exist.')

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/", "href=\"%s/" % self.site_url)


        counter = 0
        for recipient in recipients:
            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]', recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]', recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                body = body.replace('[unsubscribe_url]', recipient.noninteractive_unsubscribe_url)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]', newsletter.get_browser_view_url())

            email_to_send = Email(
                    subject=subject,
                    body=body,
                    sender=email.sender,
                    sender_display=email.sender_display,
                    reply_to=email.reply_to,
                    recipient=recipient.member.email
                    )
            email_to_send.send(connection=connection)
            counter += 1
            print "Newsletter sent to %s" % recipient.member.email

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and recipient.member.profile.email2:
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print "Newsletter sent to %s" % recipient.member.profile.email2

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()

        print "Successfully sent %s newsletter emails." % counter

        print "Sending confirmation message to creator..."
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global', 'siteurl') + newsletter.get_absolute_url()
        params = {'first_name': newsletter.email.creator.first_name,
                    'subject': newsletter.email.subject,
                    'count': counter,
                    'detail_url': detail_url}

        body = render_to_string(
                'newsletters/newsletter_sent_email_body.html', params)

        email = Email(
            recipient=newsletter.email.sender,
            subject=subject,
            body=body)

        email.send(connection=connection)

        print "Confirmation email sent."

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print 'Cache cleared!'
예제 #35
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
예제 #36
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})
예제 #37
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))
예제 #38
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            str(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            extra_context.update({
                "user": user,
                "notice": gettext(notice_type.display),
                "notices_url": notices_url,
                "current_site": current_site,
            })

            # test for request in the extra_context
            if 'request' in extra_context:
                request = extra_context['request']
            else:
                request = None

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, extra_context)

            # Strip newlines from subject
            extra_context.update({'message': mark_safe(messages['short'])})
            subject = ''.join(render_to_string(template_name='notification/email_subject.txt',
                context=extra_context, request=request).splitlines())

            extra_context.update({'message': mark_safe(messages['full'])})
            body = render_to_string(template_name='notification/email_body.txt',
                context=extra_context, request=request)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, add_tendenci_footer(body), settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)
예제 #39
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
                          })
예제 #40
0
파일: utils.py 프로젝트: goetzk/tendenci
class RecurringPaymentEmailNotices(object):
    def __init__(self):
        self.site_display_name = get_setting('site', 'global', 'sitedisplayname')
        self.site_contact_name = get_setting('site', 'global', 'sitecontactname')
        self.site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        self.reply_to_email = get_setting('module', 'payments', 'paymentrecipients')
        if not self.reply_to_email:
            self.reply_to_email = self.site_contact_email
        self.site_url = get_setting('site', 'global', 'siteurl')

        self.email = Email()
        self.email.sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
        self.email.sender_display = self.site_display_name
        self.email.reply_to = self.reply_to_email
        self.email_footer = render_to_string("email_footer.html")

        self.admin_emails = self.get_admin_emails()

    def get_admin_emails(self):
        payment_admins = get_setting('module', 'payments', 'paymentrecipients')
        if payment_admins:
            payment_admins = payment_admins.split(',')
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting('site', 'global', 'admincontactemail')).split(',')

        if admin_emails:
            admin_emails = ','.join(admin_emails)

        return admin_emails

    def get_script_support_emails(self):
        admins = getattr(settings, 'ADMINS', None)
        if admins:
            recipients_list = [admin[1] for admin in admins]
            return ','.join(recipients_list)

        return None

    def email_script_support_transaction_error(self, payment_transaction):
        """if there is an error other than transaction not being approved, notify us.
        """
        self.email.recipient = self.get_script_support_emails()
        if self.email.recipient:
            template_name = "recurring_payments/email_script_support_transaction.html"
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                self.email.priority = 1
                self.email.subject = _('Recurring payment transaction error on %(dname)s' % {
                                                                            'dname':self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_transaction_result(self, payment_transaction, success=True, **kwargs):
        """Send admins the result after the transaction is processed.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_transaction.html"
            membership = kwargs.get('membership', None)
            user_in_texas = False
            if payment_transaction.payment.state:
                if payment_transaction.payment.state.lower() in ['texas', 'tx']:
                    user_in_texas = True
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url,
                                                'user_in_texas': user_in_texas,
                                                'membership': membership,
                                                })
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                if not success:
                    self.email.subject = _('Recurring payment transaction failed on %(dname)s' % {
                                                                            'dname': self.site_display_name})
                    self.email.priority = 1
                else:
                    self.email.subject = _('Recurring payment transaction processed on %(dname)s' % {
                                                                                'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_transaction_result(self, payment_transaction, **kwargs):
        """Send customer an email after the transaction is processed.
        """
        self.email.recipient = payment_transaction.recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_transaction.html"
            membership = kwargs.get('membership', None)
            
            try:
                email_content = render_to_string(template_name,
                                               {'pt':payment_transaction,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url,
                                                'membership': membership,
                                                })
                
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                if payment_transaction.status:
                    self.email.subject = _('Payment Received ')
                else:
                    self.email.subject = _('Payment Failed ')
                self.email.subject = _("%(subj)s for %(desc)s " % {
                            'subj': self.email.subject,
                            'desc': payment_transaction.recurring_payment.description})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_no_payment_profile(self, recurring_payment):
        """Notify admin that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_no_payment_profile.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                self.email.subject = _('Payment method not setup for %(rp)s on %(dname)s' % {
                                    'rp': recurring_payment ,
                                    'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_customer_no_payment_profile(self, recurring_payment):
        """Notify customer that payment method hasn't been setup yet for this recurring payment entry.
        """
        self.email.recipient = recurring_payment.user.email
        if self.email.recipient:
            template_name = "recurring_payments/email_customer_no_payment_profile.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                self.email.subject = _('Please update your payment method for %(rp)s on %(dname)s' % {
                                    'rp': recurring_payment.description,
                                    'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass

    def email_admins_account_disabled(self, recurring_payment, user_by):
        """Notify admin that the recurring payment account is disabled.
        """
        self.email.recipient = self.admin_emails
        if self.email.recipient:
            template_name = "recurring_payments/email_admins_account_disabled.html"
            try:
                email_content = render_to_string(template_name,
                                               {'rp':recurring_payment,
                                                'user_by': user_by,
                                                'site_display_name': self.site_display_name,
                                                'site_url': self.site_url
                                                })
                self.email.body = email_content + self.email_footer
                self.email.content_type = "html"
                self.email.subject = _('Recurring Payment Account (ID:%(id)d) Disabled by %(usr)s on %(dname)s' % {
                       'id':recurring_payment.id,
                       'usr' : user_by,
                       'dname': self.site_display_name})

                self.email.send()
            except TemplateDoesNotExist:
                pass
예제 #41
0
def send_emails(emails, label, extra_context=None, on_site=True):
    """
    This method accepts a list of email addresses
    as opposed to a list of users. This is a custom method
    as opposed to send(), send_now(), and queue()

    Just send the notice to a list of emails immediately.
    No new notice created here
    notification.send_emails(email_list, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    """
    # exclude blocked emails
    emails = [e for e in emails if not Email.is_blocked(e)]
    if not emails:
        return
    
    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except NoticeType.DoesNotExist as err:
        logger.warning('Skipping notification send for "{label}": {err}'.format(
            label=label, err=err))
        # Stop here because we need a notice_type
        return None

    headers = {}
    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        str(current_site),
        reverse("notification_notices"),
    )

    formats = (
        'full.html',
        'short.txt',
        'notice.html',
    )  # TODO make formats configurable

    extra_context.update({
        "notice": gettext(notice_type.display),
        "notices_url": notices_url,
        "current_site": current_site,
        'SITE_GLOBAL_SITEURL': get_setting('site', 'global', 'siteurl'),
        'SITE_GLOBAL_SITEDISPLAYNAME': get_setting('site', 'global', 'sitedisplayname'),
    })

    # test for request in the extra_context
    if 'request' in extra_context:
        request = extra_context['request']
    else:
        request = None

    # get prerendered format messages
    messages = get_formatted_messages(formats, label, extra_context)

    if 'admin' in label:
        subject = messages['short']
        body = messages['full']

    else:
        extra_context.update({'message': mark_safe(messages['short'])})
        subject = render_to_string(
            template_name='notification/email_subject.txt',
            context=extra_context, request=request)

        extra_context.update({'message': mark_safe(messages['full'])})
        body = render_to_string(
            template_name='notification/email_body.txt',
            context=extra_context, request=request)

    if 'reply_to' in extra_context:
        reply_to = extra_context['reply_to']
        if reply_to:
            headers['Reply-To'] = reply_to
    else:
        reply_to = ''

    sender = extra_context.get('sender', '')
    if not sender:
        sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if not sender:
            sender = settings.DEFAULT_FROM_EMAIL

    sender_display = extra_context.get('sender_display', '')
    # Add quotes around display name to prevent errors on sending
    # when display name contains comma or other control characters, - jennyq
    from_display = '"%s" <%s>' % (sender_display, sender)

    if sender_display:
        headers['From'] = from_display

    recipient_bcc = extra_context.get('recipient_bcc') or []
    content_type = 'html'

    # removing newlines
    subject = ''.join(subject.splitlines())
    body = add_tendenci_footer(body)

    for email_addr in emails:
        if validate_email(email_addr):
            recipients = [email_addr]

            if recipient_bcc:
                email = EmailMessage(subject, body, sender,
                                     recipients, recipient_bcc, headers=headers)
            else:
                email = EmailMessage(subject, body, sender,
                                     recipients, headers=headers)
            email.content_subtype = content_type
    
            try:
                email.send(fail_silently=True)  # should we raise exception or not?
            except UnicodeError:
                pass

    to = ','.join(emails)
    bcc = ','.join(recipient_bcc)
    reply_to = reply_to or str()

    NoticeEmail.objects.create(
        emails=to,
        sender=sender,
        bcc=bcc,
        title=subject,
        content=body,
        reply_to=reply_to,
        from_display=from_display,
        notice_type=notice_type
    )
예제 #42
0
파일: utils.py 프로젝트: BIGGANI/tendenci
def process_export(identifier, user_id):
    field_list = [
            'guid',
            'slug',
            'timezone',
            'headline',
            'summary',
            'body',
            'source',
            'first_name',
            'last_name',
            'phone',
            'fax',
            'email',
            'website',
            'release_dt',
            'syndicate',
            'featured',
            'design_notes',
            'tags',
            'enclosure_url',
            'enclosure_type',
            'enclosure_length',
            'not_official_content',
            'entity',
        ]

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/articles/%s_temp.csv' % (identifier)

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        articles = Article.objects.filter(status_detail='active')

        for article in articles:
            items_list = []
            for field_name in field_list:
                item = getattr(article, field_name)

                if isinstance(item, datetime):
                    item = item.strftime('%Y-%m-%d %H:%M:%S')
                elif isinstance(item, date):
                    item = item.strftime('%Y-%m-%d')
                elif isinstance(item, time):
                    item = item.strftime('%H:%M:%S')
                elif isinstance(item, basestring):
                    item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/articles/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('article.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'date_today': datetime.now()}

        subject = render_to_string(
            'articles/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string(
            'articles/notices/export_ready_body.html', parms)

        email = Email(
            recipient=user.email,
            subject=subject,
            body=body)
        email.send()
예제 #43
0
파일: views.py 프로젝트: tendenci/tendenci
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)
예제 #44
0
파일: utils.py 프로젝트: goetzk/tendenci
def process_export(
        group_id,
        export_target='all',
        identifier=u'', user_id=0):
    """
    Process export for group members and/or group subscribers.
    """

    [group] = Group.objects.filter(id=group_id)[:1] or [None]
    if not group:
        return

    # pull 100 rows per query
    # be careful of the memory usage
    rows_per_batch = 100

    identifier = identifier or str(time.time())
    file_dir = 'export/groups/'

    file_path_temp = '%sgroup_%d_%s_%s_temp.csv' % (file_dir,
                                                 group.id,
                                                 export_target,
                                                identifier)

    # labels
    user_fields = ['id',
                   'first_name',
                   'last_name',
                   'email',
                   'is_active',
                   'is_staff',
                   'is_superuser']
    profile_fields = ['direct_mail',
                      'company',
                      'address',
                      'address2',
                      'city',
                      'state',
                      'zipcode',
                      'country',
                      'phone',
                      'create_dt']
    labels = user_fields + profile_fields

    field_dict = OrderedDict([(label.lower().replace(" ", "_"), ''
                               ) for label in labels])

    with default_storage.open(file_path_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_dict.keys())

        # process regular group members
        count_members = group.members.filter(
            group_member__status=True,
            group_member__status_detail='active').count()
        num_rows_processed = 0
        while num_rows_processed < count_members:
            users = group.members.filter(
                group_member__status=True,
                group_member__status_detail='active'
                ).select_related('profile'
                ).order_by('group_member__member_id')[num_rows_processed:(num_rows_processed + rows_per_batch)]
            num_rows_processed += rows_per_batch
            row_dict = field_dict.copy()
            for user in users:
                if hasattr(user, 'profile'):
                    profile = user.profile
                else:
                    profile = Profile.objects.create_profile(user)
                for field_name in user_fields:
                    if hasattr(user, field_name):
                        row_dict[field_name] = getattr(user, field_name)
                for field_name in profile_fields:
                    if hasattr(profile, field_name):
                        row_dict[field_name] = getattr(profile, field_name)
                for k, v in row_dict.items():
                    if not isinstance(v, basestring):
                        if isinstance(v, datetime):
                            row_dict[k] = v.strftime('%Y-%m-%d %H:%M:%S')
                        elif isinstance(v, date):
                            row_dict[k] = v.strftime('%Y-%m-%d')
                        else:
                            row_dict[k] = smart_str(v)

                csv_writer.writerow(row_dict.values())

    # rename the file name
    file_path = '%sgroup_%d_%s_%s.csv' % (file_dir,
                                          group.id,
                                          export_target,
                                          identifier)
    default_storage.save(file_path, default_storage.open(file_path_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_path_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(id=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('group.members_export_download',
                               args=[group.slug, export_target, identifier])
        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'group': group,
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name}

        subject = render_to_string(
            'user_groups/exports/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string(
            'user_groups/exports/export_ready_body.html', parms)

        email = Email(
            recipient=user.email,
            subject=subject,
            body=body)

        email.send()
예제 #45
0
파일: views.py 프로젝트: iniForum/tendenci
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)
예제 #46
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
    })
예제 #47
0
파일: utils.py 프로젝트: chendong0444/ams
def process_invoice_export(start_dt=None,
                           end_dt=None,
                           identifier=u'',
                           user_id=0):

    fields = [
        'id', 'guid', 'object_type', 'object_id', 'title', 'tender_date',
        'bill_to', 'bill_to_first_name', 'bill_to_last_name',
        'bill_to_company', 'bill_to_address', 'bill_to_city', 'bill_to_state',
        'bill_to_zip_code', 'bill_to_country', 'bill_to_phone', 'bill_to_fax',
        'bill_to_email', 'ship_to', 'ship_to_first_name', 'ship_to_last_name',
        'ship_to_company', 'ship_to_address', 'ship_to_city', 'ship_to_state',
        'ship_to_zip_code', 'ship_to_country', 'ship_to_phone', 'ship_to_fax',
        'ship_to_email', 'ship_to_address_type', 'receipt', 'gift',
        'arrival_date_time', 'greeting', 'instructions', 'po', 'terms',
        'due_date', 'ship_date', 'ship_via', 'fob', 'project', 'other',
        'message', 'subtotal', 'shipping', 'shipping_surcharge',
        'box_and_packing', 'tax_exempt', 'tax_exemptid', 'tax_rate', 'taxable',
        'tax', 'variance', 'discount_amount', 'total', 'payments_credits',
        'balance', 'disclaimer', 'variance_notes', 'admin_notes', 'create_dt',
        'update_dt', 'creator', 'creator_username', 'owner', 'owner_username',
        'status_detail'
    ]

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/invoices/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(fields)

        invoices = Invoice.objects.filter(status=True,
                                          update_dt__gte=start_dt,
                                          update_dt__lte=end_dt)
        for invoice in invoices:
            items_list = []
            for field_name in fields:
                item = getattr(invoice, field_name)
                if item is None:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/invoices/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('invoice.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'start_dt': start_dt,
            'end_dt': end_dt
        }

        subject = render_to_string(
            'invoices/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string('invoices/notices/export_ready_body.html',
                                parms)

        email = Email(recipient=user.email, subject=subject, body=body)
        email.send()
예제 #48
0
파일: views.py 프로젝트: iniForum/tendenci
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
                          })
예제 #49
0
파일: utils.py 프로젝트: morad7/tendenci
def process_export(export_fields='all_fields',
                   export_status_detail='',
                   identifier=u'',
                   user_id=0):
    from tendenci.apps.perms.models import TendenciBaseModel

    if export_fields == 'main_fields':
        field_list = [
            'headline', 'slug', 'summary', 'body', 'source', 'first_name',
            'last_name', 'address', 'address2', 'city', 'state', 'zip_code',
            'country', 'phone', 'phone2', 'fax', 'email', 'email2', 'website',
            'list_type', 'requested_duration', 'activation_dt',
            'expiration_dt', 'tags', 'enclosure_url', 'enclosure_type',
            'enclosure_length', 'status', 'status_detail'
        ]
    else:
        # base ------------
        base_field_list = [
            smart_str(field.name) for field in TendenciBaseModel._meta.fields
            if not field.__class__ == AutoField
        ]

        field_list = [
            smart_str(field.name) for field in Directory._meta.fields
            if not field.__class__ == AutoField
        ]
        field_list = [
            name for name in field_list if not name in base_field_list
        ]
        field_list.remove('guid')
        # append base fields at the end
        field_list = field_list + base_field_list

    identifier = identifier or int(ttime.time())
    file_name_temp = 'export/directories/%s_temp.csv' % identifier

    with default_storage.open(file_name_temp, 'wb') as csvfile:
        csv_writer = UnicodeWriter(csvfile, encoding='utf-8')
        csv_writer.writerow(field_list)

        directories = Directory.objects.all()
        if export_status_detail:
            directories = directories.filter(
                status_detail__icontains=export_status_detail)
        for directory in directories:
            items_list = []
            for field_name in field_list:
                item = getattr(directory, field_name)
                if item is None:
                    item = ''
                if item:
                    if isinstance(item, datetime):
                        item = item.strftime('%Y-%m-%d %H:%M:%S')
                    elif isinstance(item, date):
                        item = item.strftime('%Y-%m-%d')
                    elif isinstance(item, time):
                        item = item.strftime('%H:%M:%S')
                    elif isinstance(item, basestring):
                        item = item.encode("utf-8")
                    elif field_name == 'invoice':
                        # display total vs balance
                        item = 'Total: %d / Balance: %d' % (item.total,
                                                            item.balance)
                item = smart_str(item).decode('utf-8')
                items_list.append(item)
            csv_writer.writerow(items_list)

    # rename the file name
    file_name = 'export/directories/%s.csv' % identifier
    default_storage.save(file_name, default_storage.open(file_name_temp, 'rb'))

    # delete the temp file
    default_storage.delete(file_name_temp)

    # notify user that export is ready to download
    [user] = User.objects.filter(pk=user_id)[:1] or [None]
    if user and user.email:
        download_url = reverse('directory.export_download', args=[identifier])

        site_url = get_setting('site', 'global', 'siteurl')
        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        parms = {
            'download_url': download_url,
            'user': user,
            'site_url': site_url,
            'site_display_name': site_display_name,
            'export_status_detail': export_status_detail,
            'export_fields': export_fields
        }

        subject = render_to_string(
            'directories/notices/export_ready_subject.html', parms)
        subject = subject.strip('\n').strip('\r')

        body = render_to_string('directories/notices/export_ready_body.html',
                                parms)

        email = Email(recipient=user.email, subject=subject, body=body)
        email.send()
예제 #50
0
    def send_newsletter(self, newsletter_id, **kwargs):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import validate_email

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print(
                'Exiting..Please set up your newsletter email provider before proceeding.'
            )
            return

        print("Started sending newsletter...")

        if newsletter_id == 0:
            raise CommandError(
                'Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>'
            )

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError(
                'You are trying to send a newsletter that does not exist.')

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/",
                                        "href=\"%s/" % self.site_url)

        counter = 0
        for recipient in recipients:
            # skip if not a valid email address
            if not validate_email(recipient.member.email):
                continue

            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]',
                                          recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]',
                                          recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                #body = body.replace('[unsubscribe_url]', recipient.noninteractive_unsubscribe_url)
                # The unsubscribe_url link should be something like <a href="[unsubscribe_url]">Unsubscribe</a>.
                # But it can be messed up sometimes. Let's prevent that from happening.
                p = r'(href=\")([^\"]*)(\[unsubscribe_url\])(\")'
                body = re.sub(
                    p,
                    r'\1' + recipient.noninteractive_unsubscribe_url + r'\4',
                    body)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]',
                                    newsletter.get_browser_view_url())

            email_to_send = Email(subject=subject,
                                  body=body,
                                  sender=email.sender,
                                  sender_display=email.sender_display,
                                  reply_to=email.reply_to,
                                  recipient=recipient.member.email)
            print(u"Sending to {}".format(str(recipient.member.email)))
            email_to_send.send(connection=connection)
            counter += 1
            print(u"Newsletter sent to {}".format(str(recipient.member.email)))

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and validate_email(recipient.member.profile.email2):
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print(u"Newsletter sent to {}".format(
                    str(recipient.member.profile.email2)))

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()

        print("Successfully sent %s newsletter emails." % counter)

        print("Sending confirmation message to creator...")
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global',
                                 'siteurl') + newsletter.get_absolute_url()
        params = {
            'first_name': newsletter.email.creator.first_name,
            'subject': newsletter.email.subject,
            'count': counter,
            'detail_url': detail_url
        }

        body = render_to_string(
            template_name='newsletters/newsletter_sent_email_body.html',
            context=params)

        email = Email(recipient=newsletter.email.sender,
                      subject=subject,
                      body=body)

        email.send(connection=connection)

        print("Confirmation email sent.")

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print('Cache cleared!')