Beispiel #1
0
def contact(request):
    if request.method == 'POST':
        form = ContactView(request.POST)
        if form.is_valid():
            email = EmailMessage()
            email.from_email = form.cleaned_data.get('email')
            email.to = [request.POST.get('email')]
            email.topic = form.cleaned_data.get('topic')
            email.body = form.cleaned_data.get('message')

            data = EmailMessage()
            data.from_email = form.cleaned_data.get('email')
            data.to = ['*****@*****.**']
            data.topic = 'form received'
            data.body = 'message'

            my_form = form.save(commit=False)
            my_form.save()
            messages.add_message(request, messages.INFO, 'Your message has been sent. Thank you.')
            email.send()
            data.send()
            return HttpResponseRedirect('/')
    else:
        form = ContactView()

    return render(request, 'contact.html', {'form': form})
Beispiel #2
0
    def on_approved(self, application, member):
        msg = "on_approved called for %s" % application
        logger.info(msg)
        print(msg)
        mail = EmailMessage()
        mail.to = [ member.email, ]
        mail.body = """Your membership has been approved, your member id is #%d""" % member.member_id
        mail.send()

        # Auto-add the membership fee as recurring transaction
        membership_fee = env.float('MEMBEREXAMPLE_MEMBERSHIP_FEE', default=None)
        membership_tag = env.int('MEMBEREXAMPLE_MEMBERSHIP_TAG_PK', default=None)
        if membership_fee and membership_tag:
            from creditor.models import RecurringTransaction, TransactionTag
            rt = RecurringTransaction()
            rt.tag = TransactionTag.objects.get(pk=membership_tag)
            rt.owner = member
            rt.amount = -membership_fee
            rt.rtype = RecurringTransaction.YEARLY
            # If application was received in Q4 set the recurringtransaction to start from next year
            if application.received.month >= 10:
                rt.start = datetime.date(year=application.received.year+1, month=1, day=1)
            rt.save()
            rt.conditional_add_transaction()

        mailman_subscribe = env('MEMBEREXAMPLE_MAILMAN_SUBSCRIBE', default=None)
        if mailman_subscribe:
            mail = EmailMessage()
            mail.from_email = member.email
            mail.to = [ mailman_subscribe, ]
            mail.subject = 'subscribe'
            mail.body = 'subscribe'
            mail.send()
Beispiel #3
0
def send_courriel_inscrit(modele_code, inscription):
    modele_courriel = ModeleCourriel.objects.get(code=modele_code)
    message = EmailMessage()
    message.subject = modele_courriel.sujet
    modele_corps = Template(modele_courriel.corps)
    context = inscription.invitation.get_courriel_template_context()
    message.body = modele_corps.render(Context(context))
    if hasattr(settings, 'MAILING_TEST_ADDRESS'):
        message.to = [settings.MAILING_TEST_ADDRESS, ]
    else:
        message.to = [inscription.courriel, ]
    message.from_email = settings.GESTION_AG_SENDER
    message.content_subtype = "html" if modele_courriel.html else "text"
    message.send(fail_silently=True)
def receive_document(data, site=None):
    if site:
        mod_name, obj_name = get_mod_obj(site)
        if obj_name != '':
            site = getattr(__import__(mod_name, {}, {}, ['']), obj_name)

    # Get the target model (usually the supplied staging model)
    if getattr(settings, 'DJANGO_DMS_STAGING', True):
        from django_dms.models import DocumentStaging as model
    else:
        model = site.model

    # Extract data from the email
    email = message_from_file(data)
    # Save the files to the system
    documents = get_documents(email, model, site)

    from django.contrib.sites.models import Site

    # TODO: https too? Might be tricky without a request object, would need a settings variable
    host = 'http://%s' % Site.objects.get_current().domain
    message = EmailMessage()
    message.to = [email.get('Reply-To', email['From'])]
    message.subject = "Document received: %s" % email.subject  # TODO allow customisation of this
    message.body = render_to_string('django_dms/staged_document.txt', {
        'host': host,
        'dms_site': site,
        'email': email,
        'documents': documents
    })
    message.send()
Beispiel #5
0
Datei: api.py Projekt: digicyc/q
def email_kindle(request, book_id):
    """
    Email the mobi format of the book to the user's kindle email address
    """
    from django.core.mail import EmailMessage

    try:
        book = Book.objects.get(id=book_id)
    except Book.DoesNotExist:
        messages.error(request, "Book id: %s not found" % book_id)
        return HttpResponseRedirect(reverse('ebooks.views.index'))

    email = EmailMessage()
    email.subject = book.title
    email.body = book.description
    email.to = [request.user.get_profile().kindle_email,]

    headers = {'User-Agent': settings.DEFAULT_HTTP_HEADERS}
    url = Format.objects.filter(ebook=book, format='mobi')[0].ebook_file.url
    filename = os.path.basename(url)
    data = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()

    email.attach(filename, data, 'application/x-mobipocket-ebook')
    email.send()

    action.send(request.user, verb='sent', target=book)

    messages.success(request, "Successfully sent %s!" % book.title)
    return HttpResponseRedirect(reverse('ebooks.views.book_info', kwargs={'book_slug': book.slug}))
Beispiel #6
0
def contact(request, event_slug):
    event = Event.objects.filter(slug__iexact=event_slug).first()
    if not event:
        return handler404(request)
    contact_message = ContactMessage()
    form = ContactMessageForm(request.POST or None, instance=contact_message)
    if request.POST:
        if form.is_valid():
            contact_message = form.save()
            info = _("Message received from ") + contact_message.name + "\n"
            info += _("User email: ") + contact_message.email + "\n"
            contact_message.message = info + contact_message.message

            email = EmailMessage()
            email.subject = _("eventoL Contact Message from " + contact_message.name)
            email.body = contact_message.message
            email.from_email = contact_message.email
            email.to = [event.email]
            email.extra_headers = {'Reply-To': contact_message.email}
            email.send(fail_silently=False)
            event = Event.objects.filter(slug__iexact=event_slug).first()
            if not event:
                return handler404(request)
            contact_message.event = event
            contact_message.save()
            messages.success(request, _("The message has been sent. You will receive a reply by email"))
            return HttpResponseRedirect('/event/' + event_slug)
        messages.error(request, _("There was a problem sending your message. Please try again in a few minutes."))

    return render(request, 'contact-message.html', update_event_info(event_slug, request, {'form': form}, event))
Beispiel #7
0
 def get(self, request):
     """Reset the password."""
     email = request.GET.get('email', "")
     username = request.GET.get('username', "")
     user1 = UserProfile.objects.filter(email=email)
     user2 = UserProfile.objects.filter(username=username)
     user = user1 | user2
     if user.count() == 0:
         return Response("User not found",
                         status=status.HTTP_400_BAD_REQUEST)
     user = user[0]
     token = token_hex(16)
     user.set_password(token)
     user.save()
     url = f"{settings.BASE_URL}reset-password?token={token}&username={user.username}"
     email = EmailMessage()
     email.subject = "Reset Your Password"
     email.body = "You asked to reset your password, to do so please follow this link : " + url
     email.to = [user.email]
     try:
         email.send()
     except Exception as ex:
         logger.warning(MAIL_ERROR, ex)
         return Response("Error while sending email",
                         status=status.HTTP_400_BAD_REQUEST)
     return Response("Email sent !", status=status.HTTP_200_OK)
Beispiel #8
0
def send_confirmation(registrant, event ,password=None):

    message = EmailMessage()
    message.subject = u'Registration to %s' % (event.get_full_name())
    message.from_email = u'*****@*****.**'
    message.to = [registrant.email]

    details = {'name': registrant.get_full_name(),
               'username': registrant.username,
               'password': password,
               'event_name': event.get_full_name(),
               'event_scope': event.scope,
            }

    confirmation_newuser = """Dear %(name)s,

Thank you, for registering for %(event_name)s!

You may log in to the %(event_name)s website at
http://scipy.in/%(event_scope)s/login using the username -
%(username)s and the password - %(password)s.

Looking forward to meet you at %(event_name)s.

Regards,
SciPy.in Team

If you lose your password, visit: http://scipy.in/password-reset
"""

    message.body = confirmation_newuser %(details)

    message.send()
Beispiel #9
0
    def get_context_data(self, **kwargs):
        # TODO: refactor together with HolviOverdueInvoicesHandler so there's one method to format the email.
        ctx = super().get_context_data(**kwargs)
        barcode_iban = settings.HOLVI_BARCODE_IBAN
        body_template = get_template(
            'velkoja/holvi_notification_email_body.jinja')
        subject_template = get_template(
            'velkoja/holvi_notification_email_subject.jinja')
        overdue = list_invoices(status='overdue')
        for invoice in overdue:
            # Quick check to make sure the invoice has not been credited
            if float(invoice._jsondata.get('credited_sum')) > 0:
                continue

            template_iban = invoice.iban
            barcode = None
            if barcode_iban:
                template_iban = barcode_iban
                barcode = bank_barcode(barcode_iban, invoice.rf_reference,
                                       Decimal(invoice.due_sum))

            mail = EmailMessage()
            jinja_ctx = Context({
                "invoice": invoice,
                "barcode": barcode,
                "iban": template_iban,
            })
            mail.subject = subject_template.render(jinja_ctx).strip()
            mail.body = body_template.render(jinja_ctx)
            mail.to = [invoice.receiver.email]
            ctx['email'] = mail
            break
        return ctx
Beispiel #10
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
Beispiel #11
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.workshop_submission_enabled:
            return HttpResponseForbidden()

        context = self.get_context_data()
        form_content = ''
        for field in form.fields:
            form_content += "{}: {}\n".format(form[field].label, form.cleaned_data[field])

        email = EmailMessage()
        email.subject = _("Workshop in der %(ophase)s") % {'ophase': context['ophase_title']}
        email_template = loader.get_template('workshops/mail/submission.txt')
        email.body = email_template.render({
            'name': form.cleaned_data['tutor_name'],
            'title': form.cleaned_data['title'],
            'ophase': context['ophase_title'],
            'form_content': form_content
        })
        email.to = [form.cleaned_data['tutor_mail']]
        if settings is not None:
            email.reply_to = [settings.orga_email]
        email.send()

        return super().form_valid(form)
Beispiel #12
0
def send_feedback(request):

    if request.method == 'POST':
        form: ContactForm = ContactForm(request.POST)
        if form.is_valid():
            body = f'''Поступила новая заявка
            Имя: {form.data['first_name']}
            Email: {form.data['email']}
            Телефон: {form.data['phone_number']}
            Комментарий: {form.data['comment']}
            Дополнительная информация по заявке: {form.data['additional_info']}
            '''
            email = EmailMessage(
                from_email=EMAIL_SENDER,
                subject='Новая заявка',
                body=body,
            )
            comment = f"ТИП ЗАЯВКИ: {form.data['additional_info']}\n\n" \
                      f"Комментарий клиента: {form.data['comment']}"
            feedback = FeedbackHistory(first_name=form.data['first_name'],
                                       email=form.data['email'],
                                       phone_number=form.data['phone_number'],
                                       comment=comment)
            feedback.save()
            receivers = EmailReceivers.objects.filter(
                is_send_email_notifications=True)
            if receivers:
                email.to = [user.email for user in receivers]
                try:
                    email.send()
                except Exception as exc:
                    log.exception(exc)
            return HttpResponseRedirect(reverse('core-index'))
        return render(request, 'index.html', {'contact_form': form})
def receive_document(data, site=None):
    if site:
        mod_name, obj_name = get_mod_obj(site)
        if obj_name != '':
            site = getattr(__import__(mod_name, {}, {}, ['']), obj_name)

    # Get the target model (usually the supplied staging model)
    if getattr(settings, 'DJANGO_DMS_STAGING', True):
        from django_dms.models import DocumentStaging as model
    else:
        model = site.model

    # Extract data from the email
    email = message_from_file(data)
    # Save the files to the system
    documents = get_documents(email, model, site)

    from django.contrib.sites.models import Site

    # TODO: https too? Might be tricky without a request object, would need a settings variable
    host = 'http://%s' % Site.objects.get_current().domain
    message = EmailMessage()
    message.to = [email.get('Reply-To', email['From'])]
    message.subject = "Attachments received" # TODO allow customisation of this 
    message.body = render_to_string('django_dms/staged_document.txt', {'host': host,'dms_site': site, 'email': email, 'documents': documents})
    message.send()
Beispiel #14
0
def schedule_notify_email(org, occurrence, occurrence_confirmation):
    """
        to nofity by email a careprofessional if occurrence presence is 4 or 5
    """
    to = []
    oc_list = []
    oc_list.append(occurrence)

    if occurrence_confirmation.presence == 4:
        title = _('Occurrence unmarked')
    if occurrence_confirmation.presence == 5:
        title = _('Occurrence rescheduled')

    # emails address of all professional
    for p in occurrence.event.referral.professional.all():
        if p.person.notify.all() and p.person.notify.get(org_id=org.id).change_event:
            for e in p.person.emails.all():
                if not e.email in to:
                    to.append(e.email)

    if to:
        # render template
        text = Context({'oc_list':oc_list, 'title':title, 'org':org, 'showdt':True})
        template = get_template("schedule/schedule_notify_careprofessional.html").render(text)
        # sendmail
        msg = EmailMessage()
        msg.subject = u"GestorPsi - %s" % title
        msg.content_subtype = 'html'
        msg.encoding = "utf-8"
        msg.body = template
        msg.to = to
        msg.send()
        return True

    return False
Beispiel #15
0
    def bulk_email(self, request, queryset):
        emails_sent = 0
        try: 
            subject_template = Template("{% load fd_tags %} " + request.POST.get("subject"))
            message_template = Template("{% load fd_tags %} " + request.POST.get("message"))
        except Exception as e:
            self.message_user(request, "Error parsing template: " + str(e))
            return 

        email = EmailMessage(
            bcc = request.POST.get("bcc"),
            from_email = request.POST.get("from"))

        for applicant in queryset:
            c = Context({"applicant": applicant, "event": applicant.event})
            try:
                email.subject = subject_template.render(c)
                email.body = message_template.render(c)
            except Exception as e:
                self.message_user(request, "Error rendering message: " % str(e))
                break

            email.to = [request.POST.get("override_to", applicant.email)]
            email.send()
            emails_sent += 1
        
        self.message_user(request, "%s e-mails sent" % emails_sent)
Beispiel #16
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.clothing_ordering_enabled:
            return HttpResponseForbidden()

        super_return = super().form_valid(form)

        person = form.person

        orders = '\n'.join(o.info() for o in Order.get_current(person=person))
        if orders == "":
            orders = _("Keine Bestellungen")

        email = EmailMessage()
        ophase_current = Ophase.current()
        email.subject = _("Kleiderbestellung %(ophase)s") % {'ophase': str(ophase_current)}
        email_template = loader.get_template('clothing/mail/order.txt')
        email.body = email_template.render({
            'name': person.prename,
            'orders': orders,
            'editurl': self.request.build_absolute_uri(reverse('clothing:overview'))
        })
        email.to = [person.email]
        email.reply_to = [ophase_current.contact_email_address]
        email.send()

        return super_return
Beispiel #17
0
def send_invitation_to_member_via_register(user_email,registration_code):
    invitation = EmailMessage()
    invitation.subject = "Welcome to Rhizome!"
    invitation.to = [user_email]
    invite_url = "http://rhizome.org/welcome/?email=%s&registration_code=%s" % (user_email, registration_code)
    invitation.body = """
Hello, 

You have just registered as part of a group membership at Rhizome.org.
            
Rhizome.org is a global arts platform, and your group membership allows you access to Rhizome *without* having to give a donation. (All Rhizome members are required to support the organization with an annual gift; group memberships are purchased by institutions such as schools, media centers, or libraries).

Clicking on the link below will validate your account and give you access to our publications, discussion groups, ArtBase archive, community directory, and other features:

%s

If you'd like to make a donation to Rhizome, you may do so here once your account has been activated:

http://rhizome.org/support/donate/

Thank and welcome to Rhizome! 

The Rhizome Crew
    """ % (invite_url )    
    invitation.send(fail_silently=False)
Beispiel #18
0
def send_invitation_to_member_via_register(user_email, registration_code):
    invitation = EmailMessage()
    invitation.subject = "Welcome to Rhizome!"
    invitation.to = [user_email]
    invite_url = "http://rhizome.org/welcome/?email=%s&registration_code=%s" % (
        user_email, registration_code)
    invitation.body = """
Hello, 

You have just registered as part of a group membership at Rhizome.org.
            
Rhizome.org is a global arts platform, and your group membership allows you access to Rhizome *without* having to give a donation. (All Rhizome members are required to support the organization with an annual gift; group memberships are purchased by institutions such as schools, media centers, or libraries).

Clicking on the link below will validate your account and give you access to our publications, discussion groups, ArtBase archive, community directory, and other features:

%s

If you'd like to make a donation to Rhizome, you may do so here once your account has been activated:

http://rhizome.org/support/donate/

Thank and welcome to Rhizome! 

The Rhizome Crew
    """ % (invite_url)
    invitation.send(fail_silently=False)
Beispiel #19
0
def contact(request):
    context=getContext()
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ContactForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            message = EmailMessage()
            message.subject = "[{} via website]".format(form.cleaned_data["your_name"])+form.cleaned_data["subject"]
            message.reply_to = [form.cleaned_data["sender"]]
            message.to=[TO]
            message.body = form.cleaned_data["message"]
            if form.cleaned_data["copy_myself"]:
                message.cc=[form.cleaned_data["sender"]]
            message.send()
            return HttpResponseRedirect('/personal/thanks/')
        else:
        
            context.update({'form': form, "errors": True})
            return render(request, 'personal/contact.htm', context)
    # if a GET (or any other method) we'll create a blank form
    else:
        form = ContactForm()
        context.update({'form': form})
    return render(request, 'personal/contact.htm', context)
Beispiel #20
0
    def send_mail(self, connection=None):
        name = self.cleaned_data.get('name', None)
        email = self.cleaned_data.get('email')
        company = self.cleaned_data.get('company')
        phone_number = self.cleaned_data.get('phone_number')
        message = self.cleaned_data.get('message')

        if name and company:
            subject = 'Contact: {0} ({1})'.format(name, company)
        else:
            subject = 'Contact: {0}'.format(name)

        body = '{0}\n\n'.format(message)

        body = '{0}{1}\n{2}\n'.format(body, name, email)

        if phone_number:
            body = '{0}\n{1}'.format(body, phone_number)

        connection = connection or get_connection()

        # headers needs to be specified in the constructor for it to work
        e = EmailMessage(headers={'Reply-To': email})
        
        e.subject = subject
        e.body = body 
        e.to = [settings.CONTACT_EMAIL,]
        e.connection = connection
        
        e.send()
Beispiel #21
0
def sendmail(self, data):
    e = EmailMessage()
    e.body = str(data)
    e.subject = "First Ten Links in Browser"
    e.to = ADMIN_EMAIL
    e.send()
    return "Email Sent"
Beispiel #22
0
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        barcode_iban = settings.NORDEA_BARCODE_IBAN
        body_template = get_template(
            'velkoja/nordea_notification_email_body.jinja')
        subject_template = get_template(
            'velkoja/nordea_notification_email_subject.jinja')

        transaction = Transaction.objects.exclude(
            **HOLVI_EXCLUDE_KWARGS).filter(amount__lt=0).order_by('-stamp')[0]

        barcode = None
        if barcode_iban:
            barcode = bank_barcode(barcode_iban, transaction.reference,
                                   -transaction.amount)

        mail = EmailMessage()
        mail.to = [transaction.owner.email]
        render_context = Context({
            "transaction": transaction,
            "due": -transaction.amount,
            "barcode": barcode,
            "iban": barcode_iban,
        })
        mail.subject = subject_template.render(render_context).strip()
        mail.body = body_template.render(render_context)
        ctx['email'] = mail
        return ctx
Beispiel #23
0
def send_confirmation(registrant, event, password=None):

    message = EmailMessage()
    message.subject = u'Registration to %s' % (event.get_full_name())
    message.from_email = u'*****@*****.**'
    message.to = [registrant.email]

    details = {
        'name': registrant.get_full_name(),
        'username': registrant.username,
        'password': password,
        'event_name': event.get_full_name(),
        'event_scope': event.scope,
    }

    confirmation_newuser = """Dear %(name)s,

Thank you, for registering for %(event_name)s!

You may log in to the %(event_name)s website at
http://scipy.in/%(event_scope)s/login using the username -
%(username)s and the password - %(password)s.

Looking forward to meet you at %(event_name)s.

Regards,
SciPy.in Team

If you lose your password, visit: http://scipy.in/password-reset
"""

    message.body = confirmation_newuser % (details)

    message.send()
Beispiel #24
0
    def send_weekly_reminder(self):
        '''
        Sends the weekly reminder for an agent about their holiday balances
        '''
        message = \
            "Hi,\n\n" \
            "This is your weekly timetracking reminder. If the below " \
            "values are incorrect then please be sure that you have " \
            "tracked all your time correctly.\n\n" \
            "Please remember that all changes must be done before the " \
            "end of the month.\n\n" \
            "Balance for previous week: %s\n" \
            "Expected: %s\n" \
            "Difference: %s\n\n" \
            "Kind Regards,\n" \
            "Timetracking Team"

        cur = self.previous_week_balance()
        prev = self.expected_weekly_balance()
        message = message % (
            cur, prev,
            cur - prev
            )
        email = EmailMessage(from_email='*****@*****.**')
        email.body = message
        email.to = [self.user_id]
        email.subject = "Weekly timetracking reminder"
        email.send()
Beispiel #25
0
    def send_published_proposal_notification_email(self):
        proposal_notification_email = EmailMessage()
        proposal_notification_email.to = [self.author.email]
        proposal_notification_email.subject = "Rhizome Commissions Proposal Published"
        current_site = Site.objects.get_current()
        proposal_edit_url = "http://%s%s" % (current_site.domain,
                                             self.edit_url())
        proposal_view_url = "http://%s%s" % (current_site.domain,
                                             self.get_absolute_url())
        proposal_notification_email.body = """
Dear %s,

Your Rhizome commissions proposal, "%s", has been published on Rhizome as part of the %s.

You can view your proposal at this url:

%s

You may edit your proposal at any time up until %s via this url:

%s

Good luck!

-The Rhizome Team


""" % (self.author.get_profile(), self.title,
        self.cycle.title, proposal_view_url,
        self.cycle.submission_end_date.strftime("%m/%d/%Y"), proposal_edit_url)
        proposal_notification_email.send(fail_silently=True)
Beispiel #26
0
def send_event_ticket(user):
    ticket_svg = generate_ticket(user)
    ticket_data = user.get_ticket_data()

    try:
        email = EmailMessage()
        subject = _(u"Ticket for %(event_name)s event") % {'event_name': ticket_data['event'].name}
        body = _(u"Hello %(first_name)s %(last_name)s,\nHere is your ticket for %(event_name)s event." +
                 u" Please remember to print it and bring it with you the day of the event.\n" +
                 u"Regards, FLISoL %(event_name)s team.") % {'event_name': ticket_data['event'].name,
                                                             'first_name': ticket_data['first_name'],
                                                             'last_name': ticket_data['last_name']}
        email.subject = unicode(subject)
        email.body = unicode(body)
        email.to = [ticket_data['email']]
        email.attach('Ticket-' + str(ticket_data['ticket'].id).zfill(12) + '.pdf',
                     cairosvg.svg2pdf(bytestring=ticket_svg),
                     'application/pdf')
        email.send(fail_silently=False)
        ticket_data['ticket'].sent = True
        ticket_data['ticket'].save()
    except Exception as e:
        logger.error(e)
        ticket_data['ticket'].sent = False
        ticket_data['ticket'].save()
        raise e
Beispiel #27
0
    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.project = self.project
        instance.detail_level = self.detail_level

        project = self.project
        detail_level = self.detail_level
        project_progress = form.cleaned_data.get('project_progress')
        project_confidence = form.cleaned_data.get('project_confidence')
        project_recommendation = form.cleaned_data.get(
            'project_recommendation')
        now = datetime.datetime.utcnow().replace(tzinfo=utc)
        est = pytz.timezone('US/Eastern')
        submission_date = now.astimezone(est).strftime(
            '%A, %B %d %Y, %I:%M %p')

        email = EmailMessage()
        email.body = 'Project progress: ' + project_progress + '\n' + 'Project confidence: ' + project_confidence + '\n' + "Project recommendation: " + project_recommendation + '\n' + 'Submission date: ' + submission_date
        email.subject = 'Feedback has been submitted for %s (detail level %s)' % (
            project, str(detail_level))
        email.from_email = '*****@*****.**'
        email.to = ['*****@*****.**']
        email.send()

        return super(FeedbackActionMixin, self).form_valid(form)
Beispiel #28
0
def sell_existing(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    form = SellExistingBookForm()
    if request.method == 'POST':
        form = SellExistingBookForm(request.POST)
        if form.is_valid():
            copy = form.save(commit=False)
            copy.book = book
            copy.owner = request.user
            copy.pubDate = datetime.now()
            copy.save()
            messages.success(request, "Your copy of `%s` is now on sale."%\
                    book.title)
            book = copy.book
            copies = book.copy_set.filter(soldTime=None).order_by('price')
            copy_count = book.copy_set.filter(soldTime=None).count()
            for user in copy.book.subscribers.all():
                email = EmailMessage()
                email.subject = "[Kzoo LitHub] 1 new copy of '%s' on sale."\
                        %book.title
                email.body = loader.render_to_string(
                        'bookswap/notify_subscriber.html', {'book':book,
                            'copies':copies, 'copy_count':copy_count,
                            'user':user, 'settings':settings})
                email.to = [user.email]
                email.send(fail_silently=True)
            utils.opengraph_list_book(request, copy)
            return redirect('bookswap.views.book_details', book.id)
    return render(request, "bookswap/sell_existing.html",
            {'form':form, 'book':book})
Beispiel #29
0
    def email_references(self, request, queryset):
        queryset.update(event_status="checking references")
        emails_sent = 0
        try: 
            subject_template = Template("{% load fd_tags %} " + request.POST.get("subject"))
            message_template = Template("{% load fd_tags %} " + request.POST.get("message"))
        except Exception as e:
            self.message_user(request, "Error parsing template: " + str(e))
            return 

        email = EmailMessage(
            bcc = request.POST.get("bcc"),
            from_email = request.POST.get("from"))

        for applicant in queryset:
            references = json.loads(applicant.recommend_json)

            for reference in references:
                c = Context({"applicant": applicant, "event": applicant.event, "reference": reference })
                try:
                    email.subject = subject_template.render(c)
                    email.body = message_template.render(c)
                except Exception as e:
                    self.message_user(request, "Error rendering message: " % str(e))
                    break

                email.to = [request.POST.get("override_to", applicant.email)]
                email.send()
                emails_sent += 1
        
        self.message_user(request, "%s reference e-mails sent" % emails_sent)
Beispiel #30
0
    def send_created_proposal_notification_email(self):
        proposal_notification_email = EmailMessage()
        proposal_notification_email.to = [self.author.email]
        proposal_notification_email.subject = "Rhizome Commissions Proposal Created"
        current_site = Site.objects.get_current()
        proposal_edit_url = "http://%s%s" % (current_site.domain,
                                             self.edit_url())

        proposal_notification_email.body = """
Dear %s,

Thank you for creating a commissions proposal as part of the %s.

You may edit this proposal at any time up until %s via this url:

%s

Good luck!

-The Rhizome Team


""" % (self.author.get_profile(), self.cycle.title,
        self.cycle.submission_end_date.strftime("%m/%d/%Y"), proposal_edit_url)
        proposal_notification_email.send(fail_silently=True)
Beispiel #31
0
    def send_reminder_to_prospect(self, prospect):
        admin = prospect.invite_admin
        reminder = EmailMessage()
        reminder.subject = "Reminder: You've been invited to join Rhizome!"
        reminder.to = [prospect.email]
        reminder.bcc = [admin[1] for admin in settings.ADMINS]
        invite_url = "http://rhizome.org/welcome/orgsub/?email=%s&registration_code=%s" % (prospect.email, prospect.registration_code)

        reminder.body = """
Hi there, 

Just a reminder...

%s (%s) has just offered you a membership as part of the %s membership for Rhizome.org. 

Rhizome.org is a global arts platform, and your group membership allows you access to Rhizome *without* having to give a donation. (All Rhizome members are required to support the organization with an annual gift; group memberships are purchased by institutions such as schools, media centers, or libraries). 

Clicking on the link below will validate your account and give you access to our publications, discussion groups, ArtBase archive, community directory, and other features:

%s 

Thanks and welcome to Rhizome, 

The Rhizome Crew""" % (admin, admin.email, prospect.org_sub, invite_url )         
        reminder.send(fail_silently=False)
Beispiel #32
0
    def generate_message(teacher):
        any_incomplete = False
        status_lines = []
        
        for student in sorted(teacher_student_mapping[teacher], key=lambda s: (s.last_name, s.first_name)):
            complete_count = len(teacher_student_mapping[teacher][student]['complete'])
            incomplete_count = len(teacher_student_mapping[teacher][student]['incomplete'])
            total_count = complete_count + incomplete_count
            
            if teacher_student_mapping[teacher][student]['incomplete']:    
                any_incomplete = True
                status_lines.append("{student:}: {complete_count:}/{total_count:} complete".format(student=student.name, complete_count=complete_count, incomplete_count=incomplete_count, total_count=total_count))
            else:
                status_lines.append("{student:}: All complete".format(student=student.name))
        
        msg = EmailMessage()
        msg.to = [teacher.email]
        
        if any_incomplete:
            msg.subject = "Course evaluation status: Incomplete student list"
        else:
            msg.subject = "Course evaluation status: All students completed"

        msg.body = "Evaluation status for the tutees and advisees of {teacher:}:\n\n{status:}".format(status="\n".join(status_lines), teacher=teacher.name)
        msg.from_email = "*****@*****.**"
        
        return msg
def send_expired_email(membership):
    email = EmailMessage()
    email.subject = "Your Rhizome membership has expired."
    email.to = [membership.user.email]
    email.bcc = [admin[1] for admin in settings.ADMINS]
    email.body = """
Dear %s,

Did you notice that your Rhizome Membership expired?

You can renew quickly and easily here:

https://rhizome.org/support/donate/

You're missing out on all those great benefits that come with Rhizome Membership. Indispensable Resources where you can find educational programs, syllabi and residencies from around the globe to deepen your knowledge and skills. View hundreds of proposals and cast your vote for Rhizome's annual Commissions program. Flex your curator muscles with your very own Member Exhibition. Interact with artists and artworks in our comprehensive archive by leaving comments, saving artworks to your profile and access to full artwork records with the ArtBase Special Features. And on top of all that, a bonus 10 percent discount on all your purchases at the New Museum Store. 

http://rhizome.org/support/individual/

Seriously, it only takes a minute to click here and renew now! 

https://rhizome.org/support/donate/

Sincerely,

Rhizome

P.S. If you have made a donation within the past year, you are probably receiving this email because you have multiple records in our database.  If this is the case then no further action needs to be taken. Please contact %s if you believe that there has been an error that should be resolved or needs to be investigated.

+ + +

Rhizome.org is a not-for-profit 501(c)(3) organization. For U.S. taxpayers, contributions to Rhizome are tax-deductible, minus the value of any goods or services received, to the extent allowed by law.
""" % (membership.user.get_profile(), settings.SUPPORT_CONTACT[1])

    email.send(fail_silently=False)
Beispiel #34
0
def email_kindle(request, book_id):
    """
    Email the mobi format of the book to the user's kindle email address
    """
    from django.core.mail import EmailMessage

    try:
        book = Book.objects.get(id=book_id)
    except:
        return HttpResponse('Fail')

    email = EmailMessage()
    email.subject = book.title
    email.body = book.description
    email.to = (request.user.get_profile().kindle_email,)
    email.bcc = ("",) # This is a hack. I don't know why you have to set this to "" but you do otherwise it gives errors

    headers = {'User-Agent': settings.DEFAULT_HTTP_HEADERS}
    url = Format.objects.filter(ebook=book, format='mobi')[0].ebook_file.url
    filename = os.path.basename(url)
    data = urllib2.urlopen(urllib2.Request(url, headers=headers)).read()

    email.attach(filename, data, 'application/x-mobipocket-ebook')
    email.send()

    return HttpResponse('Okay')
Beispiel #35
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.workshop_submission_enabled:
            return HttpResponseForbidden()

        context = self.get_context_data()
        form_content = ''
        for field in form.fields:
            form_content += "{}: {}\n".format(form[field].label,
                                              form.cleaned_data[field])

        email = EmailMessage()
        email.subject = _("Workshop in der %(ophase)s") % {
            'ophase': context['ophase_title']
        }
        email_template = loader.get_template('workshops/mail/submission.txt')
        email.body = email_template.render({
            'name':
            form.cleaned_data['tutor_name'],
            'title':
            form.cleaned_data['title'],
            'ophase':
            context['ophase_title'],
            'form_content':
            form_content
        })
        email.to = [form.cleaned_data['tutor_mail']]
        if settings is not None:
            email.reply_to = [settings.orga_email]
        email.send()

        return super().form_valid(form)
Beispiel #36
0
    def send_receipt(self):
        receipt = EmailMessage()
        receipt.to = ["%s" % self.user.email]
        receipt.bcc = [admin[1] for admin in settings.ADMINS]
        receipt.subject = "Rhizome.org Jobs Board Posting Payment Receipt"
        receipt.body = """
Dear %s,

This confirms your payment to Rhizome in the amount of $%s for a Job Posting.

Job Title: %s
Job Posting URL: http://rhizome.org%s
Payment Amount: $%s
Payment Date: %s

Thank your for using Rhizome.org.

Sincerely,

The Rhizome Staff

""" % (self.user.get_profile(), self.amount, self.job.title,
        self.job.get_absolute_url(), self.formatted_amount(),
        self.created.strftime("%m/%d/%Y"))
        receipt.send(fail_silently=False)
def message(subject, to, from_email, msj,file):
    e = EmailMessage()
    e.subject = subject
    e.to = [to]
    e.body = msj
    e.attach_file(file)
    e.send()
Beispiel #38
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.clothing_ordering_enabled:
            return HttpResponseForbidden()

        super_return = super().form_valid(form)

        person = form.person

        orders = '\n'.join(o.info() for o in Order.get_current(person=person))
        if orders == "":
            orders = _("Keine Bestellungen")

        email = EmailMessage()
        ophase_current = Ophase.current()
        email.subject = _("Kleiderbestellung %(ophase)s") % {
            'ophase': str(ophase_current)
        }
        email_template = loader.get_template('clothing/mail/order.txt')
        email.body = email_template.render({
            'name':
            person.prename,
            'orders':
            orders,
            'editurl':
            self.request.build_absolute_uri(reverse('clothing:overview'))
        })
        email.to = [person.email]
        email.reply_to = [ophase_current.contact_email_address]
        email.send()

        return super_return
Beispiel #39
0
def contact(request, event_slug):
    event = Event.objects.filter(slug__iexact=event_slug).first()
    if not event:
        return handler404(request)
    contact_message = ContactMessage()
    form = ContactMessageForm(request.POST or None, instance=contact_message)
    if request.POST:
        if form.is_valid():
            contact_message = form.save()
            info = _("Message received from ") + contact_message.name + "\n"
            info += _("User email: ") + contact_message.email + "\n"
            contact_message.message = info + contact_message.message

            email = EmailMessage()
            email.subject = _("eventoL Contact Message from " + contact_message.name)
            email.body = contact_message.message
            email.from_email = contact_message.email
            email.to = [event.email]
            email.extra_headers = {'Reply-To': contact_message.email}
            email.send(fail_silently=False)
            event = Event.objects.filter(slug__iexact=event_slug).first()
            if not event:
                return handler404(request)
            contact_message.event = event
            contact_message.save()
            messages.success(request, _("The message has been sent. You will receive a reply by email"))
            return HttpResponseRedirect('/event/' + event_slug)
        messages.error(request, _("There was a problem sending your message. Please try again in a few minutes."))

    return render(request, 'contact-message.html', update_event_info(event_slug, request, {'form': form}, event))
Beispiel #40
0
def _send_email(data):
    message = EmailMessage()
    message.subject = data.get('subject')
    message.body = wrap(
        render_to_string('share_page/email.txt', {'data': data}), 75)
    message.to = [data.get('to_address')]
    message.send()
Beispiel #41
0
 def form_valid(self, form, **kwargs):
     pk = self.kwargs['pk']
     e = Event.objects.get(pk=pk)
     result = form.save(self.request, e.cost)
     if result is None:
         return render(self.request,
                       'buy_failure.html',
                       context={
                           'reason':
                           "Δεν επαρκεί το υπόλοιπο σας για αυτήν την αγορά"
                       })
     elif result is False:
         return redirect('/events/')
     else:
         import datetime
         amount = 0
         if e.cost > 0:
             amount = result / e.cost
         if e.availability - amount < 0:
             return render(
                 self.request,
                 'buy_failure.html',
                 context={
                     'reason':
                     "Δεν υπάρχουν αρκετά εισιτήρια για αυτή τη δραστηριότητα"
                 })
         new_balance = self.request.user.parent.coins - result
         if new_balance < 0:
             return render(
                 self.request,
                 'buy_failure.html',
                 context={
                     'reason':
                     "Δεν επαρκεί το υπόλοιπο σας για αυτήν την αγορά"
                 })
         Parent.objects.filter(pk=self.request.user).update(
             coins=new_balance)
         Event.objects.filter(pk=pk).update(availability=(e.availability -
                                                          amount))
         t = Transaction.objects.create(event=e,
                                        parent=self.request.user.parent,
                                        date=datetime.datetime.now(),
                                        amount=amount,
                                        total_cost=result)
         ##TODO add pdfcreate
         gen_pdf_from_tx(t)
         email = EmailMessage()
         email.subject = 'Το εισιτήριό σας - Lorem Ipsum'
         email.body = 'Ευχαριστούμε που μας προτιμήσατε!'
         email.to = [
             Parent.objects.get(pk=self.request.user).email,
         ]
         email.attach_file('/code/loremipsum/tickets/ticketgen/receipt.pdf')
         email.send()
         return render(self.request,
                       'buy_success.html',
                       context={
                           'transaction': t,
                           'new_balance': new_balance
                       })
Beispiel #42
0
    def get(self, request):
        tables = Table.objects.filter(user=request.user)
        context = {
            'tables': tables,
        }
        from reportlab.lib.pagesizes import letter
        from reportlab.pdfgen import canvas
        from datetime import date
        import random

        today = date.today().strftime("%d/%m/%Y")

        canvas = canvas.Canvas("/tmp/form.pdf", pagesize=letter)
        canvas.setLineWidth(.3)
        canvas.setFont('Helvetica', 12)

        canvas.drawString(30, 750, 'REGALOS S.A de CV')
        canvas.drawString(30, 735, 'FACTURA #%s' % random.randint(1, 1000))
        canvas.drawString(500, 750, today)
        canvas.line(480, 747, 580, 747)

        canvas.drawString(30, 703, 'RFC de REGALOS S.A de CV:')
        canvas.drawString(230, 703, "SAVR090503795")

        canvas.drawString(30, 683, 'Direccion de REGALOS S.A de CV:')
        canvas.drawString(
            230, 683,
            "AV JUAREZ NO. 907, PERIODISTAS, 42000, Pachuca, HIDALGO")

        canvas.drawString(30, 643, 'Nombre:')
        canvas.drawString(230, 643, "Mauricio Mejia")

        canvas.drawString(30, 623, 'RFC:')
        canvas.drawString(230, 623, "MERM971214HDFJMKR07")

        canvas.drawString(30, 603, 'Direcciom:')
        canvas.drawString(230, 603, "Calle 28 133 Progreso Nacional")

        canvas.drawString(30, 583, 'Importe:')
        canvas.drawString(230, 583, "20")

        canvas.drawString(30, 563, 'IVA:')
        canvas.drawString(230, 563, "20")

        canvas.drawString(30, 543, 'TOTAL:')
        canvas.drawString(230, 543, "20")

        canvas.save()

        email = EmailMessage()
        email.subject = "New shirt submitted"
        email.body = "Tu factura esta lista"
        email.from_email = "*****@*****.**"
        email.to = [
            "*****@*****.**",
        ]
        email.attach_file("/tmp/form.pdf")  # Attach a file directly
        email.send()

        return TemplateResponse(request, 'users/profile.html', context)
Beispiel #43
0
    def send_published_proposal_notification_email(self):
        proposal_notification_email = EmailMessage()
        proposal_notification_email.to = [self.author.email]
        proposal_notification_email.subject = "Rhizome Commissions Proposal Published"
        current_site = Site.objects.get_current()
        proposal_edit_url = "http://%s%s" % (current_site.domain, self.edit_url())
        proposal_view_url = "http://%s%s" % (current_site.domain, self.get_absolute_url())
        proposal_notification_email.body = """
Dear %s,

Your Rhizome commissions proposal, "%s", has been published on Rhizome as part of the %s.

You can view your proposal at this url:

%s

You may edit your proposal at any time up until %s via this url:

%s

Good luck!

-The Rhizome Team


""" % (self.author.get_profile(), self.title, self.cycle.title, proposal_view_url, self.cycle.submission_end_date.strftime("%m/%d/%Y"), proposal_edit_url )
        proposal_notification_email.send(fail_silently=True)
Beispiel #44
0
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        barcode_iban = settings.HOLVI_BARCODE_IBAN
        body_template = get_template('velkoja/notification_email_body.jinja')
        subject_template = get_template(
            'velkoja/notification_email_subject.jinja')
        overdue = list_invoices(status='overdue')
        for invoice in overdue:
            # Quick check to make sure the invoice has not been credited
            if float(invoice._jsondata.get('credited_sum')) > 0:
                continue

            barcode = None
            if barcode_iban:
                barcode = bank_barcode(barcode_iban, invoice.rf_reference,
                                       Decimal(invoice.due_sum))

            mail = EmailMessage()
            mail.subject = subject_template.render(
                Context({
                    "invoice": invoice,
                    "barcode": barcode
                })).strip()
            mail.body = body_template.render(
                Context({
                    "invoice": invoice,
                    "barcode": barcode
                }))
            mail.to = [invoice.receiver.email]
            ctx['email'] = mail
            break
        return ctx
Beispiel #45
0
def send_priority_email(log, priority):
    user = priority.user
    first_name = capfirst(user.first_name)
    username = user.username
    expire = priority.expire.strftime('%Y-%m-%d')
    admin_name, admin_email = settings.ADMINS[0]
    mail = EmailMessage()
    mail.subject = "Browsershots priority processing activated"
    mail.body = """
Hi %(first_name)s,

Thank you for supporting the Browsershots project.

Priority processing has been activated for %(username)s
until %(expire)s. Please let me know how it works for you,
and if you have ideas for improvement.

Cheers,
%(admin_name)s
%(admin_email)s
""".strip() % locals()
    mail.to = ['"%s %s" <%s>' % (user.first_name, user.last_name, user.email)]
    mail.bcc = [admin_email]
    mail.from_email = '"%s" <%s>' % (admin_name, admin_email)
    # mail.headers = {'Reply-To': admin_email}
    mail.send()
Beispiel #46
0
    def send( subject, body, to, from_email = None, cc = None, bcc = None, attachments = None ):
        """
        Send the email using Django's EmailMessage class

        :param: subject
        :param: body
        :param: to
        :param: from_email
        :param: cc
        :param: bcc
        :param: attachments
        :return: String
        """

        if not settings.IS_PROD:
            return True

        email = EmailMessage()
        email.content_subtype = "html"
        email.subject = subject
        email.body = body
        email.to = [to] if isinstance( to, str ) else to
        if from_email:
            email.from_email = from_email
        if cc:
            email.cc = [cc] if isinstance( cc, str ) else cc
        if bcc:
            email.bcc = [bcc] if isinstance( bcc, str ) else bcc
        if attachments:
            for attachment in attachments:
                email.attach( attachment )

        return email.send()
def send_expired_email(membership):
    email = EmailMessage()
    email.subject = "Your Rhizome membership has expired."
    email.to = [membership.user.email]
    email.bcc = [admin[1] for admin in settings.ADMINS] 
    email.body = """
Dear %s,

Did you notice that your Rhizome Membership expired?

You can renew quickly and easily here:

https://rhizome.org/support/donate/

You're missing out on all those great benefits that come with Rhizome Membership. Indispensable Resources where you can find educational programs, syllabi and residencies from around the globe to deepen your knowledge and skills. View hundreds of proposals and cast your vote for Rhizome's annual Commissions program. Flex your curator muscles with your very own Member Exhibition. Interact with artists and artworks in our comprehensive archive by leaving comments, saving artworks to your profile and access to full artwork records with the ArtBase Special Features. And on top of all that, a bonus 10 percent discount on all your purchases at the New Museum Store. 

http://rhizome.org/support/individual/

Seriously, it only takes a minute to click here and renew now! 

https://rhizome.org/support/donate/

Sincerely,

Rhizome

P.S. If you have made a donation within the past year, you are probably receiving this email because you have multiple records in our database.  If this is the case then no further action needs to be taken. Please contact %s if you believe that there has been an error that should be resolved or needs to be investigated.

+ + +

Rhizome.org is a not-for-profit 501(c)(3) organization. For U.S. taxpayers, contributions to Rhizome are tax-deductible, minus the value of any goods or services received, to the extent allowed by law.
""" % (membership.user.get_profile(), settings.SUPPORT_CONTACT[1])

    email.send(fail_silently=False)
Beispiel #48
0
    def send_receipt(self):
        receipt = EmailMessage()
        receipt.to = ["%s" % self.user.email]
        receipt.bcc = [admin[1] for admin in settings.ADMINS]
        receipt.subject = "Rhizome.org Jobs Board Posting Payment Receipt"
        receipt.body = """
Dear %s,

This confirms your payment to Rhizome in the amount of $%s for a Job Posting.

Job Title: %s
Job Posting URL: http://rhizome.org%s
Payment Amount: $%s
Payment Date: %s

Thank your for using Rhizome.org.

Sincerely,

The Rhizome Staff

""" % (
            self.user.get_profile(),
            self.amount,
            self.job.title,
            self.job.get_absolute_url(),
            self.formatted_amount(),
            self.created.strftime("%m/%d/%Y"),
        )
        receipt.send(fail_silently=False)
Beispiel #49
0
def sendEmail(subject, to, msj, file):
    e = EmailMessage()
    e.subject = subject
    e.to = [to]
    e.body = msj
    e.attach_file(file)
    e.send()
Beispiel #50
0
def enviar_email(para, asunto, cuerpo):

    e = EmailMessage()
    e.subject = asunto
    e.to = [para]
    e.body = cuerpo
    e.send()
Beispiel #51
0
def inscription_confirmee_handler(sender, **kwargs):
    send_courriel_inscrit("recu_ok", sender)

#    if sender.etablissement_delinquant():
#        modele_courriel = ModeleCourriel.objects.get(code="coti_rel")
#        message = EmailMessage()
#        message.subject = modele_courriel.sujet
#        message.body = modele_courriel.corps
#        if hasattr(settings, 'MAILING_TEST_ADDRESS'):
#            message.to = [settings.MAILING_TEST_ADDRESS,]
#        else:
#            message.to = [sender.courriel,]
#        message.from_email = settings.GESTION_AG_SENDER
#        message.content_subtype = "html" if modele_courriel.html else "text"
#        message.send(fail_silently=True)
#
    region = sender.get_etablissement().region
    nom_region = region.nom
    type_inscription = u"mandaté" if sender.est_pour_mandate() \
        else u"accompagnateur"

    subject = u"ag2017 nouvelle inscription web " + nom_region + u"-" +\
              type_inscription + u"-" + sender.get_etablissement().nom
    body = u"" + format_url(
        reverse('admin:gestion_inscriptionweb_change', args=(sender.id,)))
    envoyer_a_service('inscription', subject, body)

    message = EmailMessage()
    message.subject = subject
    message.body = body
    message.to = [adresse_email_region(region.code)]
    message.from_email = settings.GESTION_AG_SENDER
    message.send(fail_silently=True)
Beispiel #52
0
 def on_approved(self, application, member):
     msg = "on_approved called for %s" % application
     logger.info(msg)
     print(msg)
     mail = EmailMessage()
     mail.to = [ member.email, ]
     mail.body = """Your membership has been approved, your member id is #%d""" % member.member_id
     mail.send()
Beispiel #53
0
def login(request):
    if request.user.is_authenticated():
        return redirect('projekt')

    email = ''
    if request.session.has_key('email'):
        email=request.session.get('email')
        del request.session['email']

    if request.method == 'POST' and 'action' in request.POST and 'email' in request.POST:
        email = request.POST['email']
        if request.POST['action']=='login':
            password = request.POST['password']

             # Email is case-insensitive, but login is case-sensitive
            user = auth.authenticate(username=email.lower(), password=password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    return redirect('projekt')
                else:
                    messages.error(request, ERROR_MESSAGES['INACTIVEACCOUNT'] % email)

            else:
                messages.error(request, ERROR_MESSAGES['WRONGLOGINCREDENTIALS'])


        elif request.POST['action'] == 'password-lost':
            try:
                user = User.objects.get(email__iexact=email)
                recoverKey = RecoverKey.objects.getByUser(user)
                subject="Latexweboffice Passwortreset"
                url = request.build_absolute_uri(reverse('recoverpw'))+'?'+urllib.urlencode({'email': email, 'key': recoverKey.key})
                body=u"""
Hallo!

Jemand hat einen Link zur Passwortwiederherstellung angefordert: %s

Falls dies nicht von Ihnen angefordert wurde, ignorieren Sie bitte diese Email.

Mit freundlichen Grüßen,
Ihr LatexWebOfficeteam
"""
                emailsend=EmailMessage(subject, body % url)
                emailsend.to=[email]
                emailsend.send()

            except ObjectDoesNotExist:
                pass

            messages.success(request,ERROR_MESSAGES['EMAILPWRECOVERSEND']% email)

    sso_url = ''
    if 'SSO_URL' in dir(settings):
        sso_url = settings.SSO_URL

    params = {'email': email, 'IS_SSO_ENABLED': settings.IS_SSO_ENABLED, 'SSO_URL': sso_url}
    return render_to_response('login.html', params, context_instance=RequestContext(request))
Beispiel #54
0
    def get_message(self, student):
        m = EmailMessage()
        m.subject = self.render_subject(student)
        m.body = self.render_body(student)
        m.from_email = email.utils.formataddr((self.from_name, self.from_address))
        m.to = [student.email]
        m.content_subtype = self.content_subtype

        return m
Beispiel #55
0
def envoyer_a_bureau_regional(participant, subject, body):
    adresse_bureau = participant.get_region().implantation_bureau.courriel_interne
    if adresse_bureau:
        message = EmailMessage()
        message.subject = subject
        message.body = body
        message.to = adresse_bureau
        message.from_email = settings.GESTION_AG_SENDER
        message.send(fail_silently=True)