Beispiel #1
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
Beispiel #2
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 #3
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 #4
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 #5
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)
def enviaremail(subject, to, fr_mail,  message):
    e = EmailMessage()
    e.subject = subject
    e.to = [to]
    e.from_email = fr_mail
    e.body = message
    e.send()
Beispiel #7
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 #8
0
    def post(self, request):
        email = request.POST.get('email')
        try:
            user = User.objects.get(username=email)
        except User.DoesNotExist:
            ctx = {
                'error_message': 'Вы не зарегистрированы',
            }
            return render(request, 'authentication/restore.html', ctx)

        new_password = user.generate_passwd()
        user.set_password(new_password)
        user.save()
        html_content = render_to_string(
            'email_templates/restore_password.html', {
                "email": user.username,
                "password": new_password,
                "domain": 'ololo',
            })

        msg = EmailMessage()
        msg.subject = 'Восстановление пароля erofeimarkov.ru'
        msg.body = html_content
        msg.from_email = 'Erofeimarkov.ru <*****@*****.**>'
        msg.to = [user.username]
        msg.content_subtype = "html"
        sent_count = msg.send()
        ctx = {
            'error_message':
            'Вам отправлено письмо с новым паролем. Проверьте почту.',
        }
        return render(request, 'authentication/restore.html', ctx)
Beispiel #9
0
 def core(self, request_id):
     writer = WriterRegistration.object.get(request_id=request_id)
     staffs = User.objects.filter(is_staff=True)
     for i in staffs:
         message = '<div class="container" style="padding:25px;color:#999;text-align:center;background-color:#f9f9f9;">'
         message += '<div class="container" style="padding:25px;text-align:left;background-color:white;color:#373D3F;border: .05rem solid #e5e5e5;" align="center">'
         message += '<h2> Clog </h2>'
         message += '<hr />'
         message += '<h3> Hi ' + i.first_name + '</h3>'
         message += '<p>' + writer.user.first_name + ' ' + writer.user.last_name + ' applying for a writer account.</p>'
         message += '<p> With ' + writer.description + 'excuse </p>'
         message += '<form action="http://theclog.co/writer_registration">'
         message += '<input type="submit" value="Confirm writer" style="background-color:orange;color:white;border:none"/></form>'
         message += '<p> Thank! </p>'
         message += '<p> The Clog Dev team</p>'
         message += '</div>'
         message += '<p><small>Clog Corporation</small></p>'
         message += '</div>'
         message += '</div>'
         mail = EmailMessage()
         mail.subject = 'Verify' + writer.user.first_name + 'writer account '
         mail.body = message
         mail.from_email = settings.EMAIL_HOST_USER
         mail.to = [i.email]
         mail.content_subtype = "html"
         mail.send()
     return Response(status=200)
Beispiel #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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}))
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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()
Beispiel #27
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')
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 #29
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 #30
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 #31
0
def send_response_to_sender(new_to, old_to, email_type, guid='',
                            job=None, solr_job=None):
    """
    Send response to [email protected] emails

    Inputs:
    :new_to: Email address associated with the GUID address's buid
    :old_to: GUID address
    :email_type: no_job, no_contact, or contact; denotes what type of email
        is to be sent
    :guid: GUID portion of the incoming address
    :job: Job from database; includes basic job info (title, location, owner)
    :solr_job: Job from Solr; If this is passed, the job must not be expired
        and we can include a job description.
    """
    if not isinstance(new_to, (list, set)):
        new_to = [new_to]
    if isinstance(old_to, (list, set)):
        old_to = old_to[0]
    email = EmailMessage(from_email=settings.DEFAULT_FROM_EMAIL,
                         to=new_to)

    if email_type == 'no_job':
        email.subject = 'Email forward failure'
        email.body = render_to_string('redirect/email/no_job.html',
                                      {'to': old_to})
    else:
        to_parts = getaddresses(new_to)
        to = to_parts[0][0] or to_parts[0][1]
        title = ''
        description = ''
        if solr_job is not None:
            title = solr_job.get('title', '')
            description = solr_job.get('description', '')
            description = markdown.markdown(description)
        if not title:
            title = job.job_title
        render_dict = {'title': title,
                       'description': description,
                       'success': email_type == 'contact',
                       'guid': guid,
                       'recipient': to}
        email.body = render_to_string('redirect/email/job_exists.html',
                                      render_dict)
        email.content_subtype = 'html'
        email.subject = 'Email forward success'
    email.send()
Beispiel #32
0
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.guide = self.guide

        if self.form_class == FeedbackForm:
            # Gather up data for email send
            guide = self.object.guide
            version = guide.version
            project_recommendation = form.cleaned_data.get(
                'project_recommendation')
            skill_ranking = form.cleaned_data.get('skill_ranking')

            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 = 'Splash-page version: ' + str(
                version
            ) + '\n' + 'Project recommendation: ' + project_recommendation + '\n' + 'Skill ranking: ' + str(
                skill_ranking) + '\n' + 'Submission date: ' + submission_date
            email.subject = 'Feedback has been submitted for %s (splash page %s)' % (
                guide, version)
            email.from_email = '*****@*****.**'
            email.to = ['*****@*****.**']
            email.send()
        elif self.form_class == EmailSignUpForm:
            # Gather up data for email send
            submitted_email = form.cleaned_data.get('email')
            guide = self.object.guide
            version = guide.version
            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 = 'Splash-page version: ' + str(
                version
            ) + '\n' + 'Email address: ' + submitted_email + '\n' + 'Submission date: ' + submission_date
            email.subject = 'Email address has been submitted for %s (splash page %s)' % (
                guide, version)
            email.from_email = '*****@*****.**'
            email.to = ['*****@*****.**']
            email.send()
        return super(FormActionMixin, self).form_valid(form)
Beispiel #33
0
    def process_overdue(self, send=False):
        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')
        overdue = self.list_overdue()
        ret = []
        for transaction in overdue:
            # If we have already sent notification recently, do not sent one just yet
            if NotificationSent.objects.filter(
                    transaction_unique_id=transaction.unique_id).count():
                notified = NotificationSent.objects.get(
                    transaction_unique_id=transaction.unique_id)
                if (timezone.now() - notified.stamp
                    ).days < settings.HOLVI_NOTIFICATION_INTERVAL_DAYS:
                    continue
                # Also check that we have new transactions since the notification
                if UploadedTransaction.objects.count():
                    last_transaction = UploadedTransaction.objects.order_by(
                        '-last_transaction')[0].last_transaction
                    if last_transaction < notified.stamp.date():
                        continue

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

            mail = EmailMessage()
            mail.from_email = settings.VELKOJA_FROM_EMAIL
            mail.to = [transaction.owner.email]
            if settings.VELKOJA_CC_EMAIL:
                mail.cc = [settings.VELKOJA_CC_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)
            if send:
                mail.send()

            try:
                notified = NotificationSent.objects.get(
                    transaction_unique_id=transaction.unique_id)
                notified.notification_no += 1
            except NotificationSent.DoesNotExist:
                notified = NotificationSent()
                notified.transaction_unique_id = transaction.unique_id
            notified.stamp = timezone.now()
            notified.email = transaction.owner.email
            if send:
                notified.save()
            ret.append((notified, transaction))
        return ret
Beispiel #34
0
    def process_overdue(self, send=False):
        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')
        ret = []
        for invoice in overdue:
            # Quick check to make sure the invoice has not been credited
            if float(invoice._jsondata.get('credited_sum')) > 0:
                continue
            # If we have already sent notification recently, do not sent one just yet
            if NotificationSent.objects.filter(
                    transaction_unique_id=invoice.code).count():
                notified = NotificationSent.objects.get(
                    transaction_unique_id=invoice.code)
                if (timezone.now() - notified.stamp
                    ).days < settings.HOLVI_NOTIFICATION_INTERVAL_DAYS:
                    continue

            if send:
                invoice.send()

            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]
            if send:
                try:
                    mail.send()
                except Exception as e:
                    logger.exception("Sending email failed")

            try:
                notified = NotificationSent.objects.get(
                    transaction_unique_id=invoice.code)
                notified.notification_no += 1
            except NotificationSent.DoesNotExist:
                notified = NotificationSent()
                notified.transaction_unique_id = invoice.code
            notified.stamp = timezone.now()
            notified.email = invoice.receiver.email
            if send:
                notified.save()
            ret.append((notified, invoice))
        return ret
Beispiel #35
0
def sendfile(path):
    e = EmailMessage()
    e.attach_file(path)
    e.body = "Those users are active"
    e.subject = "Users Actives in our server"
    e.to = ADMIN_EMAIL
    e.send()
    return path
Beispiel #36
0
def enviaremail(subject, to, fr_mail, mensage):  #cc_mail,
    e = EmailMessage()
    e.subject = subject
    e.to = [to]
    e.fr_mail = fr_mail
    #e.cc_mail = cc_mail
    e.body = mensage
    e.send()
Beispiel #37
0
def send_repo_file(file):
    e = EmailMessage()
    e.subject = "Usuarios activos en la plataforma"
    e.to = ["<send_to>"]
    e.from_email = settings.EMAIL_HOST_USER.strip()
    e.attach_file(file)
    e.send()
    return os.path.dirname(file)
Beispiel #38
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.any_registration_enabled():
            return HttpResponseForbidden()

        try:
            if form.instance.tutor_experience is None:
                form.instance.tutor_experience = 0
            super_return = super().form_valid(form)
        except IntegrityError:
            # this should happen when unique constraints fail
            template = loader.get_template("staff/already_registered.html")
            return TemplateResponse(self.request, template)

        # the enumeration symbol
        esym = '\n * '

        form_list = []

        for field in form.fields:
            label = form[field].label
            # remove html from label
            label = label.split('<', 1)[0].strip()

            content = form.cleaned_data[field]
            #Remove all fields that are not set
            if content:
                #format Many to Many and foreign key
                if isinstance(content, QuerySet):
                    content = esym + esym.join(str(c) for c in content)
                #format True as normal language
                if isinstance(content, bool):
                    content = _('Ja')

                form_list.append('{}: {}'.format(label, content))

        form_content = '\n'.join(form_list)

        values = {
            'ophase_title': str(Ophase.current()),
            'user_prename': form.cleaned_data['prename'],
            'user_name': form.cleaned_data['name'],
            'user_email': form.cleaned_data['email'],
            'email_changedata': Ophase.current().contact_email_address,
            'form_content': form_content,
        }

        email = EmailMessage()
        email.subject = _('{ophase_title} Registrierung').format(**values)
        email.to = [
            '{user_prename} {user_name} <{user_email}>'.format(**values)
        ]
        email_template = loader.get_template('staff/mail/register.txt')
        email.body = email_template.render(values)
        email.reply_to = [Ophase.current().contact_email_address]
        email.send()

        return super_return
Beispiel #39
0
def request_for_packet(packet_name):
    #print coming here
    mail = EmailMessage()
    # check the from address from which mail is coming
    # and send a request to that mail servers to request the
    # missing packet
    mail.to = ['*****@*****.**', '*****@*****.**']
    mail.subject = "Request" + "_" + str(packet_name)
    mail.send()
Beispiel #40
0
def send_mail(ruta):
    e = EmailMessage()
    e.subject = settings.EMAIL_SUBJECT     # 'Reporte Usuarios Activos'
    e.to = settings.EMAIL_TO  #['*****@*****.**',]
    e.from_email = settings.EMAIL_HOST_USER    #'*****@*****.**'
    e.body = settings.EMAIL_BODY  #'PSI Adjunto Reporte Usuarios Activos'
    e.attach_file(ruta)
    e.send()
    return ruta
Beispiel #41
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)
Beispiel #42
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 #43
0
    def send_report(self, task):
        user = task.kwargs["user"]

        message = EmailMessage(from_email=settings.MVJ_EMAIL_FROM, to=[user.email])

        if task.success:
            message.subject = _('Report "{}" successfully generated').format(self.name)
            message.body = _("Generated report attached")
            message.attach(
                self.get_filename("xlsx"),
                task.result,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            )
        else:
            message.subject = _('Failed to generate report "{}"').format(self.name)
            message.body = _("Please try again")

        message.send()
Beispiel #44
0
def order_confirmation_mail(order_id, email):
    context = {'order': order_id}

    message = EmailMessage()
    message.content_subtype = 'html'
    message.subject = 'E-Commerce: подтверждение заказа'
    message.body = render_to_string('order_confirmation.html', context)
    message.to = [email]
    return message
Beispiel #45
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 #46
0
    def handle(self, *args, **kwargs):
        root_path = os.path.abspath(os.path.dirname(os.pardir))
        lock = os.path.join(root_path, 'lock')
        #Till the fetch_data script is running do not execute send script
        if os.path.exists(lock) == False:
            if connected_to_internet() is False:
                return None
            syncdata_folder_path = os.path.dirname(__file__).split(
                '/management')[0] + '/MailClient/syncdata'
            list_of_syncdata_folders = []
            sent_folder_path = os.path.dirname(__file__).split(
                '/management')[0] + '/MailClient/sent_syncdata_files'

            manage_path = os.path.abspath(os.path.dirname(os.pardir))
            registry_path = os.path.join(manage_path, 'Info_Registry.txt')
            if not os.path.exists(sent_folder_path):
                os.makedirs(sent_folder_path)

            try:
                # we take list of directories sorted by 'last modified time' so that changes captured first are sent first
                list_of_syncdata_folders = sorted_ls(syncdata_folder_path)
                print list_of_syncdata_folders
            except Exception as error:
                print 'File name and location is: ', str(__file__)
                print 'Error is : ', error

            for i, folder_name in enumerate(list_of_syncdata_folders):
                #send_counter = "%06d" % i
                path = syncdata_folder_path + '/' + folder_name
                #list_of_syncdata_files = os.listdir(syncdata_folder_path)
                #list_of_syncdata_files = os.listdir(path)
                if connected_to_internet() is True:
                    mail = EmailMessage()
                    tstamp = folder_name
                    #mail.subject= str(SYNCDATA_KEY_PUB) + "SYNCDATA_"+tstamp
                    mail.subject = str(
                        SYNCDATA_KEY_PUB) + "_SYNCDATA_" + tstamp

                    folder_empty = 0
                    ''''
                    for filename in list_of_syncdata_files:
                        file_path = path + '/' + filename
                        #attch Info registry with every mail
                        print file_path,filename
                        mail.attach_file(file_path)
                        folder_empty = 0
                    '''
                    print path
                    mail.attach_file(path)
                    mail.from_email = SYNCDATA_FROM_EMAIL_ID
                    mail.to = list(SYNCDATA_SENDING_EMAIL_ID)
                    if folder_empty == 0:
                        mail.send()
                    shutil.move(path, sent_folder_path)

                else:
                    return 'Internet no longer available'
def enviar_email(subject, to, from_email, body):
    e = EmailMessage()
    e.subject = subject
    e.to = [
        to,
    ]
    e.from_email = from_email
    e.body = body
    e.send()
Beispiel #48
0
    def convert_to_account(self, request, queryset):
        errors = []
        success = []
        for user in queryset:
            accounts_found = User.objects.filter(
                email=user.email).count() + User.objects.filter(
                    first_name=user.first_name,
                    last_name=user.last_name).count()
            if accounts_found > 0:
                errors.append(user.__str__())
            else:
                username = user.first_name[0] + user.last_name
                username = username.lower()
                success.append(user.__str__())
                u = User.objects.create_user(username, user.email, None)
                u.first_name = user.first_name
                u.last_name = user.last_name
                u.is_staff = True
                u.is_active = True
                password = User.objects.make_random_password()
                u.set_password(password)
                u.save()
                for group in user.orga_for.all():
                    u.groups.add(group)
                user.delete()

                mail = EmailMessage()
                mail.subject = settings.MAIL_ORGASIGNUP_SUBJECT
                mail.body = settings.MAIL_ORGASIGNUP_TEXT % {
                    'name': user.first_name,
                    'username': username,
                    'password': password
                }
                mail.to = [u.email]
                mail.send()

        if len(errors) == 0:
            self.message_user(
                request,
                "Alle ausgewählten Bewerber wurden erfolgreich in pyofahrt-Accounts konvertiert."
            )
        else:
            if len(success) > 0:
                self.message_user(
                    request,
                    "Die folgenden Bewerber wurden erfolgreich in einen pyofahrt-Account konvertiert: "
                    + ", ".join(success))
            self.message_user(
                request,
                "Die folgenden Bewerber konnten nicht in einen pyofahrt-Account konvertiert werden, da sie Duplikaten entsprechen würden: "
                + ", ".join(errors), messages.ERROR)
        if len(success) > 0:
            self.message_user(
                request,
                "Vergiss nicht, die neuen Orgas in die Mailingliste [email protected] aufzunehmen!",
                messages.WARNING)
Beispiel #49
0
def run(appID, params, hook=None):
    transformer = {
        'english-writing': 'writing', 
        'english-reading': 'reading',
        'english-listening': 'listening',
        'english-speaking': 'speaking',
        'world-citizen-after': 'wc_a',
        'solution-driven-before': 'sd_b',
        'empowering-others-after': 'eo_a',
        'horas-semanales': 'horas_semanales',
        'title': 'cargo',
        'world-citizen-before': 'wc_b',
        'self-aware-before': 'sa_b',
        'empowering-others-before': 'eo_b',
        'self-aware-after': 'sa_a',
        'lider': 'lider__nombre',
        'main-functions': 'main_functions',
        'software-knowledge': 'software_knowledge',
        'specific-knowledge': 'specific_knowledge',
        'kpis': 'critical_success_factors',
        'job-description': 'job_description',
        'solution-driven-after': 'sd_a',
        }

    podioApi = api.PodioApi(appID)
    item = podioApi.getItem(params['item_id'], no_html=True)
    
    data = tools.dictSwitch(item['values'], transformer)
    data['lider'] = item['values']['lider']['values']['title']
    data['area'] = item['values']['lider']['values']['nombre-del-cargo'].replace('LCVP ', "")
    data['horas_semanales'] = data['horas_semanales'].split('.')[0]
    print data

    generator = documentsApi.ODTTemplate('jdTemplate.odt')
    if item['values']['formato-del-jd'] == 'Word':
        fileExtension = '.odt' 
        jd = generator.renderODT(data)
    
    else:
        fileExtension = '.pdf'
        jd = generator.render(data)
    
    fileName = 'JD - %s' % data['cargo']
    email = EmailMessage()
    email.subject = fileName 
    email.body = 'Lo puedes encontrar como un archivo adjunto'
    email.from_email = '*****@*****.**'
    email.to = [item['values']['lider']['values']['correo-corporativo-aiesecandesorg'],]
    print email.to
    fileData = jd.read()
    #email.attach(fileName + fileExtension, fileData)
    #email.send()
    podioApi.appendFile(params['item_id'], fileName + fileExtension, fileData)


        
Beispiel #50
0
    def informStudents(self, request, selectedCompanies):
        print "Informing students about ",selectedCompanies;

        t = loader.get_template('company/informStudents_mail.html');
        conn = get_connection(); #for mailing
        
        for c in selectedCompanies:
            #don't send email intimations about old company arrivals wrongly as done on Sat Mar 17.

            if c.date_of_process < datetime.today(): #company process date has already passed
               print "Not informing because date of process %s has already passed!!" % (c.date_of_process)
               continue
                
            ppltoInform = c.came_for_group.get_query_set()[0].user_set.all() 
            context = Context(
                {
                    'company' : c,
                })

            body = t.render(context)

            to = [];
            for p in ppltoInform:
                to += ["*****@*****.**" % str(p.username)]; #for primary sicsrwala address
       
            #send mail actually.
            email = EmailMessage();
            email.from_email = '"Ashwini Narayan" <*****@*****.**>';
            email.subject = '[Placements] %s coming to campus' % c.name;
            #email.from = '*****@*****.**'; #left for automatic putting
            email.connection = conn;
            email.body = body;
            
            cc = [];
            # Getting the From/ CC from the placement Committee group.
            from django.contrib.auth.models import Group;
            g = Group.objects.get(name = 'placement committee')
            
            for u in g.user_set.all():
               cc.append(u.email)
            
            bcc = []
            for m in MANAGERS:
                bcc.append(list(m)[1])
            
            email.to = to + cc;
            email.bcc = bcc;
            print "to is ",email.to;
            print "bcc is ",email.bcc;
            print "body is ",email.body
            email.content_subtype='html';
            email.send();
            dir(email)
            print "Done with %s" % (c);

        self.message_user(request,"Successfully informd students");    
Beispiel #51
0
def emailSenderTwo(file):
    email = EmailMessage()
    email.subject = "Новая анкета"
    email.body = "Бланк анкеты находится во вложении этого письма"
    email.from_email = "Новый соискатель! <*****@*****.**>"
    email.to = [
        "*****@*****.**",
    ]
    email.attach_file(file)
    email.send()
 def holiday_approval_notification(self):
     '''Send the associated holiday approval for this entry.'''
     templ = get_template("emails/holiday_approved.dhtml")
     ctx = Context({"entry_date": str(self.entry_date)})
     email = EmailMessage(from_email='*****@*****.**')
     email.body = templ.render(ctx)
     email.to = [self.user.user_id]
     email.cc = self.user.get_manager_email()
     email.subject = "Holiday Request: Approved."
     email.send()
Beispiel #53
0
def generate_pdf_and_send_email(template, context, pk, model, subject, body,
                                from_email, to):
    request = RequestFactory().get(
        reverse('europarts:{model}_email'.format(model=model), args=[pk]))
    user = User.objects.get(username='******')

    kw = {'{model}_id'.format(model=model): pk}
    row_model = '{model}Row'.format(model=model)
    rows = apps.get_model('europarts', row_model).objects.filter(**kw)
    parent = apps.get_model('europarts', model).objects.get(id=pk)
    context['{model}_rows'.format(model=model)] = rows
    file_name = '{model}_email.pdf'.format(model=model)

    file_path = os.path.join(settings.MEDIA_ROOT, file_name)

    response = PDFTemplateResponse(
        request=request,
        template=template,
        filename=file_path,
        context=context,
        # show_content_in_browser=False,
        # cmd_options={'margin-top': 10,
        #              'zoom': 1,
        #              'viewport-size': '1366 x 513',
        #              'show_content_in_browser': False,
        #              'javascript-delay': 1000,
        #              'no-stop-slow-scripts': True},
    )

    pdf = response.rendered_content

    email = EmailMessage()
    email.subject = subject
    email.body = body
    email.from_email = from_email
    email.to = to

    email.attach(file_name, pdf, 'application/pdf')

    try:
        email.send()
    except:
        pass
    else:
        model = apps.get_model('europarts', model)
        Mail.objects.create(
            owner=user,
            to_email=to,
            from_email=from_email,
            subject=subject,
            content_object=model.objects.get(id=pk),
            body=body,
        )

    return
Beispiel #54
0
    def convert_to_account(self, request, queryset):
        errors = []
        success = []
        for user in queryset:
            accounts_found = User.objects.filter(email=user.email).count(
            ) + User.objects.filter(
                first_name=user.first_name, last_name=user.last_name).count()
            if accounts_found > 0:
                errors.append(user.__str__())
            else:
                username = user.first_name[0] + user.last_name
                username = username.lower()
                success.append(user.__str__())
                u = User.objects.create_user(username, user.email, None)
                u.first_name = user.first_name
                u.last_name = user.last_name
                u.is_staff = True
                u.is_active = True
                password = User.objects.make_random_password()
                u.set_password(password)
                u.save()
                for group in user.orga_for.all():
                    u.groups.add(group)
                user.delete()

                mail = EmailMessage()
                mail.subject = settings.MAIL_ORGASIGNUP_SUBJECT
                mail.body = settings.MAIL_ORGASIGNUP_TEXT % {
                    'name': user.first_name,
                    'username': username,
                    'password': password
                }
                mail.to = [u.email]
                mail.send()

        if len(errors) == 0:
            self.message_user(
                request,
                "Alle ausgewählten Bewerber wurden erfolgreich in pyofahrt-Accounts konvertiert."
            )
        else:
            if len(success) > 0:
                self.message_user(
                    request,
                    "Die folgenden Bewerber wurden erfolgreich in einen pyofahrt-Account konvertiert: "
                    + ", ".join(success))
            self.message_user(
                request,
                "Die folgenden Bewerber konnten nicht in einen pyofahrt-Account konvertiert werden, da sie Duplikaten entsprechen würden: "
                + ", ".join(errors), messages.ERROR)
        if len(success) > 0:
            self.message_user(
                request,
                "Vergiss nicht, die neuen Orgas in die Mailingliste [email protected] aufzunehmen!",
                messages.WARNING)
Beispiel #55
0
    def form_valid(self, form):
        settings = Settings.instance()
        if settings is None or not settings.any_registration_enabled():
            return HttpResponseForbidden()

        try:
            if form.instance.tutor_experience is None:
                form.instance.tutor_experience = 0
            super_return = super().form_valid(form)
        except IntegrityError:
            # this should happen when unique constraints fail
            template = loader.get_template("staff/already_registered.html")
            return TemplateResponse(self.request, template)

        # the enumeration symbol
        esym = '\n * '

        form_list = []

        for field in form.fields:
            label = form[field].label
            # remove html from label
            label = label.split('<', 1)[0].strip()

            content = form.cleaned_data[field]
            #Remove all fields that are not set
            if content:
                #format Many to Many and foreign key
                if isinstance(content, QuerySet):
                    content = esym + esym.join(str(c) for c in content)
                #format True as normal language
                if isinstance(content, bool):
                    content = _('Ja')

                form_list.append('{}: {}'.format(label, content))

        form_content = '\n'.join(form_list)

        values = {'ophase_title': str(Ophase.current()),
                 'user_prename': form.cleaned_data['prename'],
                 'user_name':  form.cleaned_data['name'],
                 'user_email': form.cleaned_data['email'],
                 'email_changedata': Ophase.current().contact_email_address,
                 'form_content': form_content,
                 }

        email = EmailMessage()
        email.subject = _('{ophase_title} Registrierung').format(**values)
        email.to = ['{user_prename} {user_name} <{user_email}>'.format(**values)]
        email_template = loader.get_template('staff/mail/register.txt')
        email.body = email_template.render(values)
        email.reply_to = [Ophase.current().contact_email_address]
        email.send()

        return super_return
Beispiel #56
0
def send_signup_mail(org, user, request, invoice):
    # notify admins
    msg = EmailMessage()
    msg.subject = u'Nova assinatura em %s' % URL_HOME
    msg.body = u'Uma nova organizacao se registrou no GestorPSI. Para mais detalhes acessar %s/gcm/\n\n' % URL_APP
    msg.body += u'Organização %s' % org
    msg.to = ADMINS_REGISTRATION
    msg.send()

    request.session['user_aux_id'] = user.id

    # notify client
    user = User.objects.get(id=request.session['user_aux_id'])
    
    msg = EmailMessage()

    msg.subject = u"Assinatura GestorPSI.com.br"

    msg.body = u"Olá, bom dia!\n\n"
    msg.body += u"Obrigado por assinar o GestorPsi.\nSua solicitação foi recebida pela nossa equipe. Sua conta está pronta para usar! "
    msg.body += u"Qualquer dúvida que venha ter é possível consultar os links abaixo ou então entrar em contato conosco através do formulário de contato.\n\n"

    msg.body += u"link funcionalidades: %s/funcionalidades-2/\n" % URL_HOME
    msg.body += u"link como usar: %s/como-usar/\n" % URL_HOME
    msg.body += u"link manual: %s/media/manual.pdf\n" % URL_DEMO
    msg.body += u"link contato: %s#contato/\n\n" % URL_HOME
    msg.body += u"Instruções no YouTube: https://www.youtube.com/playlist?list=PLJCW24WotJerfoEQvjutaG-NQg_4IgY6j\n\n"

    msg.body += u"O periodo de teste inicia em %s e termina em %s.\n" % ( invoice.start_date.strftime("%d/%m/%Y"), invoice.end_date.strftime("%d/%m/%Y") )
    msg.body += u"Antes do término do período de teste você deve optar por uma forma de pagamento aqui: %s/organization/signature/\n\n" % URL_APP

    msg.body += u"IMPORTANTE: As informações inseridas no sistema podem ser editadas mas não apagadas. Por isso, se for necessário fazer testes com informações fictícias para entender como o sistema funciona, utilize a nossa versão de demonstração: http://demo.gestorpsi.com.br\n\n"

    msg.body += u"Endereço do GestorPSI: %s\n" % URL_APP
    msg.body += u"Usuário/Login  %s\n" % request.POST.get('username')
    msg.body += u"Senha %s\n" % request.POST.get('password1')
    msg.body += u"Plano %s\n\n" % org.prefered_plan
    msg.body += u"%s" % SIGNATURE

    msg.to = [user.email]
    msg.bcc =  ADMINS_REGISTRATION
    msg.send()
Beispiel #57
0
def enviar_email(subject, to, from_email, type, code, message):
    if type == 'error':
        e = EmailMessage()
        e.subject = subject
        e.to = [
            to,
        ]
        e.from_email = from_email
        e.body = '\tType: {} \n\tCode: {} \n\tMessage: {}\n'.format(
            type, code, message)
        e.send()
Beispiel #58
0
def invoice_sendmail():

    # Invoice filter
    invoice_list = []  # list of Invoice

    # check days before expiry
    for d in INVOICE_CHECK_EXPIRY:
        # check all invoices that will be expire in 10 days.
        expiry = date.today() + timedelta(d)  # corret

        print "> check %s " % expiry
        for i in Invoice.objects.filter(
                expiry_date=expiry, status=0,
                organization__suspension=False):  # corret code
            if not i in invoice_list:
                invoice_list.append(i)

    # for invoice list
    for li in invoice_list:

        print "-- %s" % (li)

        to = []  # send mail to
        # administratror
        for e in li.organization.administrators_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email)
        # secretary
        for e in li.organization.secretary_():
            if e.profile.user.is_active and not e.profile.user.email in to:
                to.append(e.profile.user.email)

        # send email
        """
            text/body order s% of python
            1 = url pagamento
            2 = data vencimento assinatura atual
            3 = URL contato
            4 = assinatura gestorPSI
        """
        text_body = u"Bom dia.\n\nSua próxima assinatura já está disponível para pagamento em %s/organization/signature/\nVence em %s, evite ter o seu plano suspenso, pague até esta data.\n\nQualquer dúvida entre em contato pelo link %s/contato/\n" % (
            URL_APP, li.expiry_date.strftime("%d %B %Y"), URL_HOME)
        text_body += u"Quer suspender sua assinatura? Clique aqui %s/organization/suspension/\n\n%s" % (
            URL_APP, SIGNATURE)

        text_subject = u'Assinatura disponível para pagamento - gestorpsi.com.br'
        bcc = ADMINS_REGISTRATION

        msg = EmailMessage()
        msg.subject = text_subject
        msg.body = text_body
        msg.to = to
        msg.bcc = bcc
        msg.send()
Beispiel #59
0
def mail_login_token(request, email, args):
    args.setlist('next', request.GET.getlist('next'))
    relative_uri = '%s?%s' % (reverse('oneall-login'), args.urlencode())
    message = EmailMessage()
    message.subject = ugettext("Login")
    message.to = [email]
    message.body = "\n".join([
        ugettext("Complete your login using this link:"),
        request.build_absolute_uri(relative_uri),
    ])
    Thread(target=message.send, args=(True, )).start()