def handle(self, *args, **options):
        really = options['really']
        signup_extras = SignupExtraAfterpartyProxy.objects.filter(afterparty_participation=True)

        for signup_extra in signup_extras:
            vars = dict(signup_extra=signup_extra)
            subject = 'Tracon (2018): Tervetuloa kaatajaisiin!'
            sender = '*****@*****.**'
            recipient = signup_extra.person.name_and_email
            body = render_to_string('tracon2018_afterparty_message.eml', vars)

            if really:
                send_mail(
                    subject,
                    body,
                    sender,
                    [recipient],
                    fail_silently=False
                )
                print(recipient)
            else:
                print('To:', recipient)
                print('Subject:', subject)
                print()
                print(body)
                print()
                print()
Example #2
0
def contact(request):
    "Contact Page. Sends Email to email address in latest about object."
    msg = None    
    if request.method == 'POST':
        form = ContactForm(request.POST) 
        if form.is_valid():
            # Get Sarah's Email from her About obj
            try:
                about = About.objects.latest()
                email = about.email
            except About.DoesNotExist:
                email = '*****@*****.**'
            # Get data from form and mail to sarah
            name = form.cleaned_data['name']
            sender = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']            
            recipients = ['*****@*****.**']
    
            from django.core.mail import send_mail
            send_mail(subject, message, sender, recipients)
            
            msg = "Thank you for contacting Sarah"
            form = None
    else:
        form = ContactForm()
    return render_to_response('contact.html', {
        'msg': msg,
        'form': form,
    }, context_instance=RequestContext(request))
Example #3
0
    def handle(self, *args, **options):
        to_ampr = []
        with open(AMPR_DNS_QUEUE, 'r') as f:
            for line in f.readlines():
                split = line.split()
                pair = (split[-1], split[0])

                # download ampr host file only during first iteration
                if not self.ampr_hosts:
                    self.get_ampr_hosts()

                if pair in self.ampr_hosts:
                    # exists, skipping
                    continue

                # TODO: delete stale records

                to_ampr.append(line)

        if to_ampr:
            send_mail('NM HamWAN DNS update', ''.join(set(to_ampr)),
                AMPR_DNS_FROM, [AMPR_DNS_TO], fail_silently=False)

        with open(AMPR_DNS_QUEUE, 'w') as f:
            f.write("")
Example #4
0
def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
            firstname = user_form['first_name'].value()
            lastname = user_form['last_name'].value()
            subject = 'Report Viewer Registration: {}, {}'.format(
                lastname, firstname)
            message = 'User {} {} <{}> has registered and needs to be vetted.'.format(
                firstname, lastname, user.email)
            send_mail(subject, message, '*****@*****.**',
                      ['*****@*****.**'], fail_silently=False)
        else:
            print user_form.errors
    else:
        user_form = UserForm()
    context = {'user_form': user_form, 'registered': registered}
    context.update(csrf(request))
    return render_to_response('viewer/register.html', context,
                              context_instance=RequestContext(request))
Example #5
0
def comment_notification(comment):
    subject = u"Комментарий к вашему объявлению на сайте buy.fizteh.ru"
    message = u"""Уважаемый пользователь,
    
    К Вашему объявлению \"%s\" добавлен комментарий.
    
    Чтобы посмотреть его, перейдите по ссылке: http://buy.fizteh.ru/item/%d
    
    С уважением, команда Барахолки.""" % (
        comment.advert.name,
        comment.advert.id,
    )
    # Send mail to the author of advert.
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [comment.advert.user.email], True)
    # Send mail to the other users that have commented the advert.
    all_comments = Comment.objects.filter(advert=comment.advert)
    commenters = []
    for com in all_comments:
        if com.user != comment.advert.user and com.user not in commenters:
            commenters.append(com.user.email)
    if len(commenters) == 0:
        return
    subject = u"Ответ на комментарий к объявлению на сайте buy.fizteh.ru"
    message = u"""Уважаемый пользователь,
    
    К объявлению \"%s\", которое вы комментировали, добавлен новый комментарий.
    
    Чтобы посмотреть его, перейдите по ссылке: http://buy.fizteh.ru/item/%d
    
    С уважением, команда Барахолки.""" % (
        comment.advert.name,
        comment.advert.id,
    )
    send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, commenters, True)
 def init_password_email(self, user):
     site = Site.objects.get_current()
     ctx_dict = {'site': site, 'organization': settings.TELEMETA_ORGANIZATION, 'usr': user}
     subject = render_to_string(self.subject_template, ctx_dict)
     subject = ''.join(subject.splitlines())
     message = render_to_string(self.message_template, ctx_dict)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
    def create(self, request):
        # Form validated so we don't have to check any arguments.
        notification_type  = request.POST.get('type')
        patient_id = request.POST.get('patient_id')
        case_identifier = request.POST.get('case_identifier')
        message = request.POST.get('message')
        destination = request.POST.get('destinations')

        n = models.Notification(patient_id=patient_id,
                                client=destination,
                                procedure_id=case_identifier,
                                message=message,
                                delivered=False)


        if notification_type == 'SMS':
            sms.send_sms_notification(n)
        elif notification_type == 'EMAIL':
            subject = request.POST.get('email_subject')
            try:
                send_mail(subject, n.message, '*****@*****.**',
                          destination, fail_silently=False)
                n.delivered = True
            except Exception, e:
                logging.error("Could not send email: %s." % e)
def send_template(request):
    from django.conf import settings
    from django.core.mail import send_mail

    try:
        shop = request.shop
        email = request.GET.get("email", None)
        id = long(request.GET.get("id", None))

        notification = EmailNotification.objects.filter(id=id, shop=shop).get()

        send_mail(
            notification.render_dummy(notification.subject),
            notification.render_dummy(notification.body),
            settings.EMAIL_FROM,
            recipient_list=[email],
            fail_silently=True,
        )

        request.flash["message"] = unicode(_("Email sent."))
        request.flash["severity"] = "success"

    except Exception, e:
        request.flash["message"] = unicode(_("Can't send email."))
        request.flash["severity"] = "error"
Example #9
0
def site_message_form(request):
    form = f.SiteMessageForm(request.POST or None)
    if request.method=='POST':
        if form.is_valid():
            form.save()
            from django.core.mail import send_mail
            send_mail('[e-pyfan.com]' + form.cleaned_data['subj'], form.cleaned_data['body'], settings.ADMINS[0][1], [settings.ADMINS[0][1]], fail_silently=False)
            return redirect('/result/message_sent/')
    base_template = t.Template(m.Template.objects.get(code='BASE_00').body)
    child_template = t.Template('<P><B>Отправка сообщения:</b></p>{% if form.is_multipart %}' + \
              '<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}' + \
              '{% else %}' + \
              '<form method="post" action="">{% csrf_token %}' + \
              '{% endif %}' + \
              '<table>' + \
              '{{ form.as_table }}' + \
              '</table><input type="submit" value="Отправить" />'
              '</form>')
    context = {}
    context.update(csrf(request))
    context_instance = RequestContext(request, context)
    context_instance.update({'form':form})    
    content = child_template.render(context_instance)
    menu_items = m.StandardSection.objects.filter(is_menu_item='Y', is_active='Y').order_by('order')
    base_items = {'menu_items':menu_items, 'content':content, 'STATIC_URL':settings.STATIC_URL, 'curr_date':datetime.datetime.now(tz=pytz.timezone('Europe/Moscow'))}
    context_instance.update(base_items)
    return HttpResponse(base_template.render(context_instance))    
Example #10
0
def send_notifications(project, log_entries):
    """Send notifications for one project.

    :project: The project to send notifications for.
    :param log_entries: log entries to be sent.
    """
    rendered_entries = []
    for entry in log_entries:
        if entry.action in TEMPLATE_MAPPING:
            tmpl = TEMPLATE_MAPPING[entry.action]
            msg = loader.render_to_string(tmpl, {'log': entry})
            rendered_entries.append(msg)

    subject_tmpl = _('{prefix}New updates available for project "{project}"')
    subject = subject_tmpl.format(**{'prefix': settings.EMAIL_SUBJECT_PREFIX,
                             'project': project.name})
    body = ''.join(rendered_entries)

    mails = []
    members = project.projectmember_set.all()

    for member in members:
        mails.append(member.mail or member.user.email)

    send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, mails,
              fail_silently=False)
Example #11
0
File: tests.py Project: 6ft/django
    def test_connection_arg(self):
        """Test connection argument to send_mail(), et. al."""
        mail.outbox = []

        # Send using non-default connection
        connection = mail.get_connection('mail.custombackend.EmailBackend')
        send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, 'Subject')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        send_mass_mail([
            ('Subject1', 'Content1', '*****@*****.**', ['*****@*****.**']),
            ('Subject2', 'Content2', '*****@*****.**', ['*****@*****.**']),
        ], connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 2)
        self.assertEqual(connection.test_outbox[0].subject, 'Subject1')
        self.assertEqual(connection.test_outbox[1].subject, 'Subject2')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        mail_admins('Admin message', 'Content', connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message')

        connection = mail.get_connection('mail.custombackend.EmailBackend')
        mail_managers('Manager message', 'Content', connection=connection)
        self.assertEqual(mail.outbox, [])
        self.assertEqual(len(connection.test_outbox), 1)
        self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message')
Example #12
0
def on_going_process_user(user, test=False):
    now = datetime.datetime.utcnow()
    date = now - datetime.timedelta(days=21)
    user_location = user.sql_location
    if not user_location:
        return

    facilities = []
    if user_location.location_type.name == 'district':
        facilities = user_location.get_children()
    elif user_location.location_type.name == 'region':
        facilities = SQLLocation.objects.filter(domain=user.domain,
                                                parent__parent__location_id=user.location._id)
    fac = set()
    for facility in facilities:
        sp = facility.supply_point_id
        if not sp:
            continue
        transactions_exist = StockTransaction.objects.filter(
            case_id=sp,
            type="stockonhand",
            report__date__gte=date
        ).exists()
        if not transactions_exist:
            fac.add(unicode(facility.name))
    verified_number = user.get_verified_number()
    if fac and verified_number:
        message = ONGOING_NON_REPORTING % " \n".join(fac)
        if not test:
            send_sms_to_verified_number(verified_number, message)
        else:
            send_test_message(verified_number, message)
        if can_receive_email(user, verified_number):
            email = str(user.email)
            send_mail('ONGOING NON REPORTING', message, '*****@*****.**', [email])
Example #13
0
def contact(request):
    success = False
    sender = ""
    email = ""
    university = ""
    message = ""

    if request.method == "POST":
        form = ContactForm(request.POST)

        if form.is_valid():
            success = True
            sender = form.cleaned_data['sender']
            email = form.cleaned_data['email']
            university = form.cleaned_data['university']
            message = form.cleaned_data.get('message')

            recipients = ['*****@*****.**']
            
            send_mail('Contact EV', 'Email: %s - University: %s - Message: %s' % (email, university, message), sender, recipients)
            return HttpResponseRedirect('/thanks/')

    else:
        form = ContactForm()
    
    ctx = {'form':form, 'sender':sender, 'email':email, 'university':university, 'message':message, 'success':success}
    
    return render_to_response('contact.html', ctx, context_instance=RequestContext(request))
Example #14
0
def add_new(request):
    # get information from POST method
    if request.method == 'POST':
        title = request.POST['title']
        story = request.POST['story']
        # if author is anonymous
        try:
            is_anonymous = request.POST['anonymous']
            author = 'Аноним'
        except:
            author = request.POST['author']

        # if user don't enter any of the required fields
        if title == '' or story == '' or author == '':
            msg = 'Пожалуйста, заполните все поля.'
            return render(request, 'articles/addnew.html', {'msg': msg})
        else:
            # save new story to database
            a = Article(article_title=title, article_text=story, article_author=author)
            a.save()
            link = 'http://the-trembling.info/articles/administration/list/{0}/'.format(a.id)
            mail_body = story + '\n-----------------------------------------\n' + 'Автор: ' + author + '\n' + link
            send_mail(title, mail_body, '*****@*****.**',
                      ['*****@*****.**'], fail_silently=False)
            return HttpResponseRedirect(reverse('articles:index'))

    else:
        return render(request, 'articles/addnew.html')
Example #15
0
def report_reminder_process_user(user, test=False):
    now = datetime.datetime.utcnow()
    date = now - datetime.timedelta(days=7)

    if not user.location or user.location.location_type.administrative:
        return
    sp = SupplyPointCase.get_by_location(user.location)
    if not sp:
        return
    transaction_exists = StockTransaction.objects.filter(
        case_id=sp._id,
        type="stockonhand",
        report__date__gte=date
    ).exists()
    if sp and not transaction_exists and user.get_verified_number():
        message = REPORT_REMINDER % (user.name, user.location.name)
        verified_number = user.get_verified_number()
        if not test:
            send_sms_to_verified_number(verified_number, message)
        else:
            send_test_message(verified_number, message)

        if can_receive_email(user, verified_number):
            email = str(user.email)
            send_mail('REPORT REMINDER', message, '*****@*****.**', [email])
Example #16
0
def activate(request, userid):
    if request.method == 'POST':
        if hashlib.md5(request.POST['pw']).hexdigest() == settings.MASTER_PASSWORD:
            try:
                pendinguser = PendingUsers.objects.get(pk=int(userid))
            except:
                return HttpResponseNotFound("No such user", content_type="text/plain")
            clamuser = CLAMUsers(username=pendinguser.username, password=pendinguser.password,fullname=pendinguser.fullname, institution=pendinguser.institution, mail=pendinguser.mail,active=True)
            try:
                clamuser.save()
            except IntegrityError:
                return HttpResponseForbidden("User is already activated", content_type="text/plain")
            send_mail('Webservice account on ' + settings.DOMAIN , 'Dear ' + clamuser.fullname + '\n\nYour webservice account on ' + settings.DOMAIN + ' has been reviewed and activated.\n\n(this is an automated message)', settings.FROMMAIL, [clamuser.mail] + [ x[1] for x in settings.ADMINS ] , fail_silently=False)
            return HttpResponse("Succesfully activated", content_type="text/plain")
        else:
            return HttpResponseForbidden("Invalid password, not activated", content_type="text/plain")

    else:
        try:
            pendinguser = PendingUsers.objects.get(pk=int(userid))
        except:
            return HttpResponseNotFound("No such pending user, has probably already been activated", content_type="text/plain")

        c = RequestContext(request)
        c.update(csrf(request))
        return render_to_response('activate.html',{'userid': userid},context_instance=c)
Example #17
0
def signup(request):
	if request.method == 'POST':
		form = SignupForm(request.POST)
		print(form.data)
		print(form.is_valid())
		if form.is_valid():
			form.save()

			username = form.data['username']
			email = form.data['email']
			print(username,email)
			salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
			activation_key = hashlib.sha1((salt+email).encode('utf-8')).hexdigest()
			key_expires = datetime.datetime.today() + datetime.timedelta(1)

			# Create and save user profile
			user = User.objects.get(email=email)
			new_profile = UserProfile(user=user, activation_key=activation_key,
				key_expires=key_expires)
			new_profile.save()

			# Send email with activation key
			email_subject = 'Account confirmation'
			email_body = "Hi %s, thanks for signing up. To activate your account, click this link within \
			48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key)
			send_mail(email_subject, email_body, '*****@*****.**',
				[email], fail_silently = False)
			return render(request, 'sign_up_success.html')
		else:
			return render(request, 'confirm_expired.html')
	else:
		return render(request, 'sign_up.html')
Example #18
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = request.POST.get('subject', '')
            message = request.POST.get('message', '')
            name = request.POST.get('name', '')
            from_email = '%s <%s>' % (name,
                                      request.POST.get('from_email', ''))
            recipient_list = [mail_tuple[1] for mail_tuple in settings.ADMINS]
            try:
                t = loader.get_template('reviewapp/email_contact.txt')
                c = Context({
                            'name': name,
                            'message': message,
                            'site_domain': Site.objects.get_current().domain,
                            'site_name': Site.objects.get_current().name, })
                send_mail(subject, t.render(c), from_email, recipient_list,
                          fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            messages.success(request, _('Message sent successfully.'))
            return HttpResponseRedirect('/contact/')
        else:
            messages.warning(request, _('Please fill out all fields correctly.'))
    else:
        if request.user.is_authenticated():
            form = ContactForm(user=request.user)
        else:
            form = ContactForm()

    return render_to_response('reviewapp/contact.html', {
                              'form': form, },
                              context_instance=RequestContext(request))
Example #19
0
    def deliver(self, recipient, notice_type, extra_context):
        # TODO: require this to be passed in extra_context

        context = self.default_context()
        context.update({
            "recipient": recipient,
            # "sender": sender,
            "notice": ugettext(notice_type.display),
        })
        context.update(extra_context)

        messages = self.get_formatted_messages((
            "short.txt",
            "full.txt"
        ), notice_type.label, context)

        subject = "".join(render_to_string("notification/email_subject.txt", {
            "message": messages["short.txt"],
        }, context).splitlines())

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

        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient.email])
Example #20
0
def payment_receiver(*args, **kwargs):
    try:
        order_id = int(kwargs.get('order_id'))
    except (ValueError, TypeError):
        order_id = None

    try:
        order = Order.objects.get(id=order_id)
    except Order.DoesNotExist:
        return

    # order_payed_sum = Decimal(0)
    # for payment in PaymentNotification.objects.filter(InvId=order_id):
    #     order_payed_sum += Decimal(payment.OutSum)

    order_payed_sum = PaymentNotification.objects.filter(order_id=order.id).values('order_id').annotate(
        amount_sum=Sum('amount'))[0]['amount_sum']

    if order_payed_sum >= order.total_price():
        order.is_paid = True
        order.save()
        send_mail(
            u'Оплата заказа',
            render_to_string('email/order_payed.html', {'order': order, 'payed_sum': order_payed_sum,
                                                        'domain_name': 'mayflo.ru'}),
            settings.DEFAULT_FROM_EMAIL,
            [settings.DEFAULT_TO_EMAIL],
            fail_silently=False
        )
Example #21
0
    def post(self, request, *args, **kwargs):
        serialized = UserSerializer(data=request.DATA)
        if serialized.is_valid():

            user = User.objects.create_user(
                    serialized.initial_data['username'],
                    serialized.initial_data['email'],
                    serialized.initial_data['password'],
                    )
            user.is_active = False
            user.save()

            username = serialized.initial_data['username']
            email = serialized.initial_data['email']

            salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
            activation_key = hashlib.sha1(str(salt).encode('utf-8')+str(email).encode('utf-8')).hexdigest()

            key_expires = datetime.datetime.today() + datetime.timedelta(2)
            user = User.objects.get(username=username)

            new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires)
            new_profile.save()
            email_subject = "Подтверждение регистрации на instagram-mephi.ru"
            email_body = "Привет %s, спасибо, что зарегистрировался на нашем сайте! Чтобы активировать свой аккаунт зайди" \
                         " по ссылке ниже, у тебя есть 48 часов! \
                                 http://127.0.0.1:8000/confirm/%s" % (username, activation_key)

            send_mail(email_subject, email_body, '*****@*****.**', [email], fail_silently=False)
            return Response(status=status.HTTP_201_CREATED,)
        else:
            return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Example #22
0
def contact(request):

	title = 'Contact Us'
	title_align_center = True
	form = ContactForm(request.POST or None)

	if form.is_valid():
		form_email = form.cleaned_data.get("email")
		form_full_name = form.cleaned_data.get("full_name")
		form_message = form.cleaned_data.get("message")

		subject = 'Site info'
		from_email = settings.EMAIL_HOST_USER
		to_email = [from_email, '*****@*****.**']
		contact_message = "%s: %s via %s"%(
				form_full_name, 
				form_message, 
				form_email)

		send_mail(subject, 
				contact_message, 
				from_email, 
				to_email, 
				fail_silently=False)
		#print form.cleaned_data
		#print email, full_name, message

	context = {
		"form": form,
		"title": title,
		"title_align_center": title_align_center
	}
	return render(request, "forms.html", context)
Example #23
0
 def send_email(self):
     send_mail(
         self.cleaned_data["subject"],
         self.cleaned_data["message"],
         self.cleaned_data["email"],
         [settings.CONTACT_EMAIL],
     )
Example #24
0
def contactpage(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()

            # Sending email.
            subject = form.cleaned_data['subject']
            email = [form.cleaned_data['email'], settings.EMAIL_HOST_USER, ]
            message = form.cleaned_data['message']

            send_mail(subject, message, settings.EMAIL_HOST_USER, email, fail_silently=False)

            url = reverse('contact:message-sent')
            return HttpResponseRedirect(url)
    else:
        form = ContactForm(
            initial={
                'name': u'Kolo\u017ei Robert',
                'email': u'*****@*****.**',
                'subject': u'[Django] Test from gmail to eunet.rs subject',
                'message': u'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et nunc id felis condimentum ullamcorper nec a orci. Morbi placerat convallis pharetra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin volutpat id massa et pulvinar. Etiam est ligula, imperdiet sed sollicitudin vitae, vehicula id nunc. Maecenas at sollicitudin nunc, at fringilla nisi. Duis egestas lorem tristique, suscipit nisi nec, commodo sem. Nulla ac eros nec leo tincidunt bibendum a eget felis. Nunc consectetur enim ligula, vel egestas quam rutrum in.',
                'web_site': u'http://www.robertkolozsi.org'
            }
        )

    context = {
        'form': form,
    }
    return render_to_response('contact/index.html',
                              context,
                              context_instance=RequestContext(request))
Example #25
0
 def send(self):
     subject = _(u'Invitation to a Duel')
     link = '%s/duel/accept/%s/' % (settings.SITE_HOST, self.code)
     template = get_template('registration/invitation_email.txt')
     context = Context({'link': link, 'sender': self.sender.get_full_name(), 'topic':self.ring.topic})
     message = template.render(context)
     send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
Example #26
0
def register(request):
    error=''
    if request.method=='GET':
        return render_to_response('usercenter_register.html',{},context_instance=RequestContext(request))
    else:
        username=request.POST['username'].strip()
        email=request.POST['email'].strip()
        password=request.POST['password'].strip()
        re_password=request.POST['re_password'].strip()
        if not username or not email or not password:
            error='任何字段不能为空'
        if password != re_password:
            error='两次密码不一致'
        if User.objects.filter(username=username).count() > 0:
            error='用户已存在'
        if not error:
            user=User.objects.create_user(username=username,email=email,password=password)
            user.is_active=False
            user.save()

            new_code=str(uuid.uuid4()).replace('-','')
            expire_time=datetime.datetime.now()+datetime.timedelta(days=2)
            code_recode=ActivateCode(owner=user,code=new_code,expire_timestamp=expire_time)
            code_recode.save()

            activate_link="http://%s%s" %(request.get_host(),reverse('usercenter_activate',args=[new_code]))
            send_mail(u'python部落激活邮件',u'激活地址:%s' %  activate_link , '*****@*****.**', [email],fail_silently=False)
        else:
            return render_to_response('usercenter_register.html',{'error':error},context_instance=RequestContext(request))
        return redirect(reverse('login'))
Example #27
0
    def send_email(user, workout, delta):
        '''
        Notify a user that a workout is about to expire

        :type user User
        :type workout Workout
        :type delta datetime.timedelta
        '''

        # Update the last notification date field
        user.userprofile.last_workout_notification = datetime.date.today()
        user.userprofile.save()

        # Compose and send the email
        translation.activate(user.userprofile.notification_language.short_name)
        context = {}
        context['site'] = Site.objects.get_current()
        context['workout'] = workout
        context['expired'] = True if delta.days < 0 else False
        context['days'] = abs(delta.days)

        subject = _('Workout will expire soon')
        message = loader.render_to_string('workout/email_reminder.tpl', context)
        mail.send_mail(subject,
                       message,
                       EMAIL_FROM,
                       [user.email],
                       fail_silently=True)
Example #28
0
def contact(request):
    title_align_center ="True"
    form = ContactForm(request.POST or None)
    if form.is_valid():
        # for key in form.cleaned_data:
        #     print(key)
        #     print(form.cleaned_data.get(key))
        form_email = form.cleaned_data.get("email")
        form_name = form.cleaned_data.get("name")
        subject = form.cleaned_data.get("subject")
        form_message = form.cleaned_data.get("message")
        # print (email,name,subject,message)
        from_email = settings.EMAIL_HOST_USER
        to_email = [from_email, '*****@*****.**']

        contact_message = "%s: %s via %s" % (
            form_name,
            form_message,
            form_email)

        send_mail(subject,
                  contact_message,
                  from_email,
                  to_email,
                  fail_silently=False)  # SEE THIS MAKE IT TRUE IT DOESNOT WORK

    context = {
        "form": form,
        "title_align_center":title_align_center,
    }
    return render(request, "contact.html", context)
 def handle(self, *args, **options):
   yesterday = datetime.datetime.now()-datetime.timedelta(7)
   pe = Enrollment.objects.pending_evaluation()
   pe = pe.filter(evaluation_date__gte=yesterday)
   if pe.count() and options.get("verbosity") > 0:
     print "sending %s evaluation emails"%pe.count()
   for enrollment in pe:
     if not enrollment.user.email:
       continue
     _dict = {
       'evaluation': enrollment,
       'la_key': LimitedAccessKey.new(enrollment.user),
       'domain': settings.SITE_URL,
       'settings': settings
     }
     subject = "Please evaluate the class you took from %s"%settings.SITE_NAME
     if enrollment.session.course.get_private_files():
       subject = "Course files and pending evaluation for %s"%enrollment.session.course
     send_mail(
       subject,
       render_to_string("email/pending_evaluation.html",_dict),
       settings.DEFAULT_FROM_EMAIL,
       [enrollment.user.email]
     )
     enrollment.emailed=True
     enrollment.save()
def send(subj, msg, emails):
    """ Helper method to send emails """
    msg += "\n\n-- CU Assassins"
    try:
        send_mail(prefix + subj, msg, settings.DEFAULT_FROM_EMAIL, emails)
    except Exception, e:
        print >> sys.stderr, traceback.format_exc()
Example #31
0
def appearances(request):
    if request.method == 'GET':
        queryset = Appearance.objects.all()
        serializer = AppearanceShortSerializer(queryset, many=True)
        return HttpResponse(JSONRenderer().render(serializer.data))
    #save information from form into appearance request
    elif request.method == 'POST':
        data = json.loads(request.body)
        appearance_serializer = AppearanceSerializer(data=data['appearance'])
        if appearance_serializer.is_valid():
            appearance = appearance_serializer.save()
            appearance_serializer = AppearanceSerializer(appearance)

        else:
            return HttpResponse(appearance_serializer.errors, status=400)

        customer_serializer = CustomerSerializer(data=data['customer'])
        #after adding customer to db, send confirmation email to customer confirming contact information and event information.
        if customer_serializer.is_valid():
            customer = customer_serializer.save()
            customer.save()
            appearance.customer = customer
            appearance.save()
            html_message = render_to_string(
                'customer_confirmation.html', {
                    'name': appearance.name,
                    'date': appearance.date,
                    'start_time': appearance.start_time,
                    'end_time': appearance.end_time,
                    'first_name': customer.first_name,
                    'last_name': customer.last_name,
                    'phone': customer.phone,
                    'email': customer.email,
                    'organization': appearance.organization,
                    'location': appearance.location,
                    'description': appearance.description,
                    'status': appearance.status,
                    'special_instructions': appearance.special_instructions,
                    'expenses_and_benefits': appearance.expenses_and_benefits,
                    'cheerleaders': appearance.cheerleaders,
                    'showgirls': appearance.showgirls,
                    'parking_info': appearance.parking_info,
                    'outside_orgs': appearance.outside_orgs,
                    'performance_required': appearance.performance_required,
                })
            send_mail(
                'Event request confirmation',
                'Thanks for requesting a Superfrog appearance! Here is a confirmation message for the event request: \n'
                + '\n' + 'Customer Contact Information \n' +
                'Customer Name: ' + customer.first_name + ' ' +
                customer.last_name + '\n' + 'Phone Number: ' +
                str(customer.phone) + '\n' + 'Customer email: ' +
                customer.email + '\n' + ' \n' + 'Appearance Information \n' +
                'Start Time: ' + appearance.name + '\n' + 'Date: ' +
                str(appearance.date) + '\n' + 'Start Time: ' +
                str(appearance.start_time) + '\n' + 'End Time: ' +
                str(appearance.end_time) + '\n' +
                'Organization requesting event: ' + appearance.organization +
                '\n' + 'Location: ' + appearance.location + '\n' +
                'Description: ' + appearance.description + '\n' + 'Status: ' +
                appearance.status + '\n' + 'Special Instructions: ' +
                appearance.special_instructions + '\n' +
                'Expenses and Benefits: ' + appearance.expenses_and_benefits +
                '\n' + 'Cheerleaders: ' + appearance.cheerleaders +
                ' Showgirls: ' + appearance.showgirls + '\n' + '\n' +
                'Our team will review your request within the next two weeks. You will receive an email updating you on our decision when it is made. Thanks and Go Frogs!',
                '*****@*****.**', [customer.email],
                fail_silently=False,
                html_message=html_message)
        else:
            return HttpResponse(appearance_serializer.errors, status=400)
        appearance_serializer = AppearanceSerializer(appearance)
        return HttpResponse(status=200)
    else:
        return HttpResponseBadRequest()
Example #32
0
def process(request):
    text="wrong"
    rows=[]
    diseasetable=[]
    
    aboutDisease=[]
    twolists=[]
    unique_data=[]
    final=[]
    if request.method == 'POST':
        myform = SymptomForm(request.POST)
        if myform.is_valid():
            #print (request.session.session_key)
            


        #user = User.objects.get(pk=uid)
            #print(uid)
        #print (user.username, user.get_full_name(), user.email)
            text=myform.cleaned_data['symptom_text']
            stop = set(stopwords.words('english'))
            important_words=[]
            for i in text.lower().split():
              if i not in stop:
                important_words.append(i)

            for i in range(0,len(important_words)):
                print (important_words[i])

            #cur=conn.cursor()
            
            query="select distinct D.Disease as disease, D.BodyLocation as body_location, X.rank as rank , D.Symptoms from DiseaseSymptoms D join ( select T.disease_id, sum(T.norm_tfidf) as rank from (select disease_id, norm_tfidf from norm_symptoms_tfidf where term in %s )T group by T.disease_id order by sum(T.norm_tfidf) desc) X on X.disease_id=D.DiseaseID order by X.rank desc limit 10" % repr(important_words).replace('[','(').replace(']',')') 
            cur.execute(query)
            #transaction.commit_unless_managed()
            rows = cur.fetchall()
            #print(type(row))
            #print (rows)
            for row in rows:
                diseasetable.append([row[0],row[1],row[2]])
                aboutDisease.append(row[3])

            #print("disease table ")
            top2diseases=diseasetable[0][0]+"|"+diseasetable[1][0]
            querytime=time.strftime("%H:%M:%S")
            querydate=time.strftime("%d/%m/%Y")
            if(request.session.session_key!=None):
             session = Session.objects.get(session_key=request.session.session_key)
             history_query="select * from history where id=%s"

             uid = session.get_decoded().get('_auth_user_id')
             cur.execute(history_query,uid)
             history=cur.fetchall()
             print(history)
             name_query="select name,email from authtools_user where id=%s"
             cur.execute(name_query,uid)
             results=cur.fetchall()
             name=results[0][0]
             email= results[0][1]
             data4=([uid,top2diseases,querydate,querytime])
             q="insert into history values(%s,%s,%s,%s)"
             cur.execute(q,data4)
             diseaseText="These are the descriptions of diseases you possibly have"
             i=1
             for d in aboutDisease:
                diseaseText=diseaseText+"\n"+str(i)+d+"\n"
                i=i+1
             send_mail('hospital@home symptom checker', diseaseText, '*****@*****.**', [email], fail_silently=False)

            print(diseasetable)
            bodyloc={}
            total_body_locs=0
            for i in range(0,len(rows)):
                bl=diseasetable[i][1]
                print(bl)
                if bl==None:
                    break
                if bodyloc.get(bl):
                    bodyloc[bl]=bodyloc[bl]+1
                else:
                    bodyloc[bl]=1

                total_body_locs=total_body_locs+1

            proportion=0
            temp=sorted(bodyloc.items(), key=lambda x: (-x[1], x[0]))
            bodyloc = dict(temp)
            print(temp)
            #print(total_body_locs)
            #print(bodyloc)
            #for key in bodyloc:
             #   proportion=int(float(bodyloc[key])/total_body_locs*10)
                #print(proportion)
              #  doctors=fillDoctors(key,proportion)

            for item in temp:
                proportion=int(float(item[1])/total_body_locs*10)
                #print(proportion)
                fillDoctors(item[0],proportion)
            #cur.close()
            twolists=zip(diseasetable,aboutDisease)
            temp=[]
            for row,ad in twolists:
              temp.append([row[0],ad])
            unique_data = [list(x) for x in set(tuple(x) for x in temp)]
            final=[]
            for y in unique_data:
              for z in diseasetable:
                if(z[0]==y[0]):
                  final.append([y[0],y[1],z[2]])
                  break
            final=sorted(final,key=itemgetter(2),reverse=True)
    return render(request, 'symptomchecker/symptomchecker.html', {'rows':diseasetable,'form':text,'doctors':doctors,'twolists':twolists,'unique_data':final})
Example #33
0
def email_winner(entry):
    if(entry.winner):
        address = entry.email_address;
        subject = "Congratulations"
        body = "Congratulations! You have won " + entry.giveaway.prize.name
        send_mail(subject, body, "*****@*****.**", [address])
 def check_status(self):
     try:
         send_mail(EMAIL_SUBJECT, EMAIL_MESSAGE, EMAIL_FROM, EMAIL_TO)
     except SMTPException as message:
         raise HealthCheckException(message)
def student_management(request, name="All Students"):
    # gets current researcher for use later
    added_by = Researcher.objects.get(email=request.user)

    # if the label with label_name = name is not found load default of All Students
    if not SubjectLabel.objects.filter(label_name=name, researcher=added_by):
        name = "All Students"

    # if the table for All Students is deleted or does not exist, make it and add all students the researcher
    # has added and add them to it.
    if not SubjectLabel.objects.filter(label_name='All Students', researcher=added_by):
       all_stu_lbl = SubjectLabel().create_label('All Students', added_by)
       all_students = Student.objects.filter(added_by=added_by, is_active=True)
       for stud in all_students:
           all_stu_lbl.students.add(stud)

    # if researcher presses a submit button
    if request.method == "POST":
        if request.POST.get('student_email'):  # create new student
            form = SendEmail(request.POST)

            if form.is_valid():
                email = form.cleaned_data.get('student_email')
                if not Student.objects.filter(email=email):
                    # creates a student with blank fist and last names, then the password is set to unusable
                    first_name = ""
                    last_name = ""
                    password = ""
                    user = Student.objects.create(email=email, first_name=first_name, last_name=last_name, password=password, added_by=added_by, )
                    user.set_unusable_password()

                    # adds a student to the "All Students" label
                    label = SubjectLabel.objects.get(label_name="All Students", researcher=added_by)
                    label.students.add(user)

                    # collects the current domain of the website and the users uid
                    current_site = get_current_site(request)
                    site = current_site.domain
                    uid = urlsafe_base64_encode(force_bytes(user.pk))

                    # creates the subject and message content for the emails
                    subject = 'Activate your Simulated Conversations account'
                    message = 'Hi, \nPlease register here: \nhttp://' + site + '/student/register/'\
                        + uid + '\n'

                    # sends the email
                    send_mail(subject, message, '*****@*****.**', [email], fail_silently=False)
                else:
                    messages.error(request, 'Student already exists', fail_silently=False)
            else:
                messages.error(request, 'Invalid input', fail_silently=False)

        if request.POST.get('email'):
            form = AddToLabel(request.POST)

            if form.is_valid():
                email = form.cleaned_data.get('email')
                # checks to make sure user exists
                if Student.objects.filter(email=email):

                    # adds student to current label
                    user = Student.objects.get(email=email)
                    label = SubjectLabel.objects.get(label_name=name, researcher=added_by)
                    label.students.add(user)

                else:
                    messages.error(request, 'Student does not already exist', fail_silently=False)
            else:
                messages.error(request, 'Invalid input', fail_silently=False)

        if request.POST.get('label_name'):  # create new label
            save_folder = NewLabel(request.POST)
            if save_folder.is_valid():
                label_name = save_folder.cleaned_data.get("label_name")

                # if the label does not already exist, create it
                if not SubjectLabel.objects.filter(label_name=label_name, researcher=added_by):
                    SubjectLabel().create_label(label_name, added_by)
                else:
                    messages.error(request, 'Label name already exists',
                                   fail_silently=False)

    # creates the table for the labels
    all_lbl = SubjectLabel.objects.filter(researcher=added_by).values('label_name')
    label_table = LabelList(all_lbl, prefix="1-")
    RequestConfig(request, paginate={"per_page": 20}).configure(label_table)

    # creates the table for the students in current label
    if not name == 'All Students':
        stu_contents = SubjectLabel.objects.filter(label_name=name, researcher=added_by).values(
            'students__first_name',
            'students__last_name',
            'students__email',
            'students__registered')
        student_table = StudentList(stu_contents, prefix="2-")
        RequestConfig(request, paginate={"per_page": 20}).configure(student_table)
    else:
        stu_contents = Student.objects.filter(added_by=added_by).values(
            'first_name',
            'last_name',
            'email',
            'registered')
        student_table = AllStudentList(stu_contents, prefix="2-")
        RequestConfig(request, paginate={"per_page": 10}).configure(student_table)

    return render(request, 'student_management.html',  {"name": name, "form": AddToLabel(), "form2": NewLabel(),
                                                        "form3": SendEmail(), 'stu_table': student_table,
                                                        'lbl_table': label_table})
Example #36
0
def acceptAppearance(request, id=None):
    if request.method == 'PATCH':
        appearance_id = Appearance.objects.get(pk=id)
        constant = Constant.objects.get()
        appearance_id.status = "Accepted"
        appearance_id.save()
        #if there are cheerleaders in the event, email cheerleader captain.
        if appearance_id.cheerleaders != "None":
            send_mail(
                'Cheerleaders Requested at Superfrog Appearance',
                'A new event request has been approved by the admin- the customer has requested cheerleaders-'
                + appearance_id.cheerleaders +
                '! Below is the appearance info confirmation: \n' + '\n' +
                'Customer Contact Information \n' + 'Customer Name: ' +
                appearance_id.customer.first_name + ' ' +
                appearance_id.customer.last_name + '\n' + 'Phone Number: ' +
                str(appearance_id.customer.phone) + '\n' + 'Customer email: ' +
                appearance_id.customer.email + '\n' + ' \n' +
                'Appearance Information \n' + 'Name: ' + appearance_id.name +
                '\n' + 'Date: ' + str(appearance_id.date) + '\n' +
                'Start Time: ' + str(appearance_id.start_time) + '\n' +
                'End Time: ' + str(appearance_id.end_time) + '\n' +
                'Organization requesting event: ' +
                appearance_id.organization + '\n' + 'Location: ' +
                appearance_id.location + '\n' + 'Description: ' +
                appearance_id.description + '\n' + 'Status: ' +
                appearance_id.status + '\n' + '\n' + 'Thanks and Go Frogs!',
                '*****@*****.**',
                [constant.cheerleader_captain_email],
                fail_silently=False,
            )
        #if there are showgirls in the event, email showgirl captain.
        if appearance_id.showgirls != "None":
            send_mail(
                'Showgirls Requested at Superfrog Appearance',
                'A new event request has been approved by the admin- the customer has requested cheerleaders-'
                + appearance_id.showgirls +
                '! Below is the appearance info confirmation: \n' + '\n' +
                'Customer Contact Information \n' + 'Customer Name: ' +
                appearance_id.customer.first_name + ' ' +
                appearance_id.customer.last_name + '\n' + 'Phone Number: ' +
                str(appearance_id.customer.phone) + '\n' + 'Customer email: ' +
                appearance_id.customer.email + '\n' + ' \n' +
                'Appearance Information \n' + 'Name: ' + appearance_id.name +
                '\n' + 'Date: ' + str(appearance_id.date) + '\n' +
                'Start Time: ' + str(appearance_id.start_time) + '\n' +
                'End Time: ' + str(appearance_id.end_time) + '\n' +
                'Organization requesting event: ' +
                appearance_id.organization + '\n' + 'Location: ' +
                appearance_id.location + '\n' + 'Description: ' +
                appearance_id.description + '\n' + 'Status: ' +
                appearance_id.status + '\n' + '\n' + 'Thanks and Go Frogs!',
                '*****@*****.**',
                [constant.showgirl_captain_email],
                fail_silently=False,
            )

        #superfrog email notification
        superfrog = User.objects.all()
        slist = []
        for s in superfrog:
            slist.append(s.email)

        superfrog_notification = render_to_string(
            'superfrog_notification.html', {
                'name': appearance_id.name,
                'date': appearance_id.date,
                'start_time': appearance_id.start_time,
                'end_time': appearance_id.end_time,
                'first_name': appearance_id.customer.first_name,
                'last_name': appearance_id.customer.last_name,
                'phone': appearance_id.customer.phone,
                'email': appearance_id.customer.email,
                'organization': appearance_id.organization,
                'location': appearance_id.location,
                'description': appearance_id.description,
                'status': appearance_id.status,
                'special_instructions': appearance_id.special_instructions,
                'expenses_and_benefits': appearance_id.expenses_and_benefits,
                'cheerleaders': appearance_id.cheerleaders,
                'showgirls': appearance_id.showgirls,
                'parking_info': appearance_id.parking_info,
                'outside_orgs': appearance_id.outside_orgs,
                'performance_required': appearance_id.performance_required,
            })

        send_mail(
            'Superfrog Available Appearance Notification',
            'A new event request has been approved by the admin- we need you to sign up! Below is the appearance info confirmation: \n'
            + '\n' + 'Customer Contact Information \n' + 'Customer Name: ' +
            appearance_id.customer.first_name + ' ' +
            appearance_id.customer.last_name + '\n' + 'Phone Number: ' +
            str(appearance_id.customer.phone) + '\n' + 'Customer email: ' +
            appearance_id.customer.email + '\n' + ' \n' +
            'Appearance Information \n' + 'Name: ' + appearance_id.name +
            '\n' + 'Date: ' + str(appearance_id.date) + '\n' + 'Start Time: ' +
            str(appearance_id.start_time) + '\n' + 'End Time: ' +
            str(appearance_id.end_time) + '\n' +
            'Organization requesting event: ' + appearance_id.organization +
            '\n' + 'Location: ' + appearance_id.location + '\n' +
            'Description: ' + appearance_id.description + '\n' + 'Status: ' +
            appearance_id.status + '\n' + '\n' + 'Thanks and Go Frogs!',
            '*****@*****.**',
            slist,
            fail_silently=False,
            html_message=superfrog_notification)

        return HttpResponse(status=201)
Example #37
0
def signUp(request, id=None, sId=None):
    if request.method == 'PATCH':
        appearance_id = Appearance.objects.get(pk=id)
        superfrog_id = Superfrog.objects.get(user_id=sId)
        superfrog_appearance = SuperfrogAppearance(superfrog=superfrog_id,
                                                   appearance=appearance_id)
        superfrog_appearance.save()
        appearance_id.status = "Assigned"
        appearance_id.save()
        #superfrog email confirming sign up
        superfrog_message = render_to_string(
            'superfrog_confirmation.html', {
                'name': appearance_id.name,
                'date': appearance_id.date,
                'start_time': appearance_id.start_time,
                'end_time': appearance_id.end_time,
                'first_name': appearance_id.customer.first_name,
                'last_name': appearance_id.customer.last_name,
                'phone': appearance_id.customer.phone,
                'email': appearance_id.customer.email,
                'organization': appearance_id.organization,
                'location': appearance_id.location,
                'description': appearance_id.description,
                'status': appearance_id.status,
                'special_instructions': appearance_id.special_instructions,
                'expenses_and_benefits': appearance_id.expenses_and_benefits,
                'cheerleaders': appearance_id.cheerleaders,
                'showgirls': appearance_id.showgirls,
                'parking_info': appearance_id.parking_info,
                'outside_orgs': appearance_id.outside_orgs,
                'performance_required': appearance_id.performance_required,
            })
        #customer email confirming appearance
        customer_message = render_to_string(
            'appearance_confirmation.html', {
                'name': appearance_id.name,
                'date': appearance_id.date,
                'start_time': appearance_id.start_time,
                'end_time': appearance_id.end_time,
                'first_name': appearance_id.customer.first_name,
                'last_name': appearance_id.customer.last_name,
                'phone': appearance_id.customer.phone,
                'email': appearance_id.customer.email,
                'organization': appearance_id.organization,
                'location': appearance_id.location,
                'description': appearance_id.description,
                'status': appearance_id.status,
                'special_instructions': appearance_id.special_instructions,
                'expenses_and_benefits': appearance_id.expenses_and_benefits,
                'cheerleaders': appearance_id.cheerleaders,
                'showgirls': appearance_id.showgirls,
                'parking_info': appearance_id.parking_info,
                'outside_orgs': appearance_id.outside_orgs,
                'performance_required': appearance_id.performance_required,
                'cost': str(appearance_id.cost),
            })
        #admin email
        send_mail(
            'Appearance Confirmation',
            'You are scheduled to appear at an event! Here is the appearance info: \n'
            + '\n' + 'Customer Contact Information \n' + 'Customer Name: ' +
            appearance_id.customer.first_name + ' ' +
            appearance_id.customer.last_name + '\n' + 'Phone Number: ' +
            str(appearance_id.customer.phone) + '\n' + 'Customer email: ' +
            appearance_id.customer.email + '\n' + ' \n' +
            'Appearance Information \n' + 'Name: ' + appearance_id.name +
            '\n' + 'Start Time: ' + str(appearance_id.start_time) + '\n' +
            'End Time: ' + str(appearance_id.end_time) + '\n' + 'Date: ' +
            str(appearance_id.date) + '\n' +
            'Organization requesting event: ' + appearance_id.organization +
            '\n' + 'Location: ' + appearance_id.location + '\n' +
            'Description: ' + appearance_id.description + '\n' + 'Status: ' +
            appearance_id.status + '\n' + '\n' + 'Thanks and Go Frogs!',
            '*****@*****.**', [User.objects.get(pk=sId).email],
            fail_silently=False,
            html_message=superfrog_message)
        #
        send_mail(
            'Superfrog Appearance Confirmation',
            'Your event has been accepted- and Superfrog will be there! Here is the appearance info confirmation: \n'
            + '\n' + 'Customer Contact Information \n' + 'Customer Name: ' +
            appearance_id.customer.first_name + ' ' +
            appearance_id.customer.last_name + '\n' + 'Phone Number: ' +
            str(appearance_id.customer.phone) + '\n' + 'Customer email: ' +
            appearance_id.customer.email + '\n' + ' \n' +
            'Appearance Information \n' + 'Name: ' + appearance_id.name +
            '\n' + 'Date: ' + str(appearance_id.date) + '\n' + 'Start Time: ' +
            str(appearance_id.start_time) + '\n' + 'End Time: ' +
            str(appearance_id.end_time) + '\n'
            'Organization requesting event: ' + appearance_id.organization +
            '\n' + 'Location: ' + appearance_id.location + '\n' +
            'Description: ' + appearance_id.description + '\n' + 'Status: ' +
            appearance_id.status + '\n' + '\n' + 'Cost: $' +
            str(appearance_id.cost) + '\n' +
            'In order to complete the booking of this appearance, you must pay through this link: https://secure.touchnet.com/C21491_ustores/web/classic/product_detail.jsp?PRODUCTID=221'
            + '\n' + 'Enter the cost of the appearance ($' +
            str(appearance_id.cost) +
            ') in the field titled \'Donation Amount\'.\n Thanks and Go Frogs!',
            '*****@*****.**', [appearance_id.customer.email],
            fail_silently=False,
            html_message=customer_message)
        return HttpResponse(superfrog_appearance, status=201)
Example #38
0
from energyspy.viewer.models import *
import datetime,sys,pprint
from django.db.models import Q
from django.forms.models import model_to_dict
from django.core.mail import send_mail


def timestamp():
    return '[%s]'%datetime.datetime.now()

now = datetime.datetime.now()
today= now.replace(hour=0,minute=0,second=0,microsecond=0)
active_sensors    =   Sensors.objects.all()

#time_now   =    datetime.time(hour=now.hour,minute=now.minute,second=now.second)

if active_sensors:
    for sensor in active_sensors:
        
        last_measurement_date   =   Measurements.objects.filter(sensor=sensor).order_by('datetimestamp').reverse()[0].datetimestamp
        
        if ( now - last_measurement_date  > datetime.timedelta(minutes = 45)):
            a   =   now - last_measurement_date
            text = u'Sensor mac: %s - No ha respondido desde hace %s'%(sensor.mac,a)
            send_mail('[ENERGYSPY] Aviso de SENSOR NO RESPONDE', text, '*****@*****.**',['*****@*****.**','*****@*****.**','*****@*****.**'],fail_silently=False)

sys.exit(1)
        
                
Example #39
0
 def email_user(self, subject, message, from_email=None, **kwargs):
     """
     Sends an email to this User.
     """
     send_mail(subject, message, from_email, [self.primary_email], **kwargs)
Example #40
0
 def email_user(self, subject, message, from_email=None):
     "Sends an e-mail to this User."
     from django.core.mail import send_mail
     send_mail(subject, message, from_email, [self.email])
Example #41
0
 def email_user(self, subject, message, from_email=None, **kwargs):
     send_mail(subject, message, from_email, [self.email], **kwargs)
Example #42
0
def send_message(user_id, name, user_info, subject, body):
  """
  send email to google users. user_id is the email for google.
  """
  send_mail(subject, body, settings.SERVER_EMAIL, ["%s <%s>" % (name, user_id)], fail_silently=False)
Example #43
0
    def handle(self, *args, **options):

        # update the year of all past feast dates
        management.call_command('update_feast_year')

        (start_date, end_date) = get_email_date_range()
        latest_pull_date = get_latest_price_pull_date()

        (feasts, products) = get_email_feasts_products(start_date, end_date,
                                                       latest_pull_date)
        deals = get_email_deals(latest_pull_date)

        message = render_to_string(
            'api/templates/email.txt', {
                'feasts':
                feasts,
                'products':
                products,
                'start_date':
                start_date.strftime('%B %d'),
                'end_date':
                end_date.strftime('%B %d'),
                'latest_pull_date':
                latest_pull_date.strftime('%B %d, %Y'),
                'price_per_liter_score_percent':
                str(int(PRICE_PER_LITER_SCORE_PERCENT * 100)),
                'price_per_size_score_percent':
                str(int(PRICE_PER_SIZE_SCORE_PERCENT * 100)),
                'deals_min_price_score':
                DEALS_MIN_PRICE_SCORE,
            })

        html_message = render_to_string(
            'api/templates/email.html', {
                'feasts':
                feasts,
                'products':
                products,
                'deals':
                deals,
                'start_date':
                start_date.strftime('%B %d'),
                'end_date':
                end_date.strftime('%B %d'),
                'latest_pull_date':
                latest_pull_date.strftime('%B %d, %Y'),
                'price_per_liter_score_percent':
                str(int(PRICE_PER_LITER_SCORE_PERCENT * 100)),
                'price_per_size_score_percent':
                str(int(PRICE_PER_SIZE_SCORE_PERCENT * 100)),
                'deals_min_price_score':
                DEALS_MIN_PRICE_SCORE,
            })

        recipient_list = settings.EMAIL_RECIPIENTS

        success = send_mail(
            subject='Bevendo: Your Weekly Drinking with the Saints Cocktails',
            from_email=settings.SENDER_EMAIL,
            recipient_list=recipient_list,
            message=message,
            html_message=html_message,
        )
        # print(success)
        # print(html_message)
        # print(message)

        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        print('send_cocktail_recommendations script ran', dt_string)
Example #44
0
def register(request):
    if not request.user.is_authenticated:
        try:
            if request.method == 'POST':
                first_name=request.POST['first_name']
                last_name=request.POST['last_name']
                username=request.POST['username']
                email=request.POST['email']
                phone=request.POST['phone']
                password=request.POST['password']
                password2=request.POST['password2']
                pattern="[a-z]+[A-Z]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+[a-z|A-Z|@|#|0-9]+"
                if password == password2:
                    if match(pattern,password):
                            if CustomUser.objects.filter(username=username).exists():
                                messages.error(request,'usernmae exsits')
                                return redirect('register')
                            else:
                                if CustomUser.objects.filter(email=email).exists():
                                    messages.error(request,'email exsits')
                                    return redirect('register')
                                else:
                                    user=CustomUser.objects.create_user(username=username,password=password,first_name=first_name,last_name=last_name,email=email,phone=phone)
                                    #auth.login(request,user)
                                    #messages.success(request,'you are now logged in')
                                    #return redirect('index')
                                    user.is_active=False
                                    user.save()
                                    current_site = get_current_site(request)
                                    email_subject = 'Activate Your Account'
                                    message_tosend = render_to_string('accounts/activate_account.html', {
                                        'user': user,
                                        'domain': current_site.domain,
                                        'uid': urlsafe_base64_encode(force_bytes(user.id)),
                                        'token': account_activation_token.make_token(user),
                                        
                                    })
                                    send_mail(
                                            email_subject,
                                            message_tosend,'*****@*****.**',[email],
                                            fail_silently=False
                                    )
                                    messages.success(request,'check your email for activating your account')
                                    return redirect('login')
                    else:
                        messages.error(request,'password must contain atleast one uppercase and one digit')
                        return redirect('register')

                else:
                    messages.error(request,'password not match')
                    return redirect('register')
            else:
                return render(request,'accounts/register.html')
        except :
            if request.user.is_authenticated:
                auth.logout(request)
            messages.error(request,'Error Exits: we are trying to solve try again later')
            return redirect('login')
    else:
        messages.error(request,'You are already logged in')
        return redirect('dashboard')
Example #45
0
import os
from django.core.mail import send_mail
os.environ['DJANGO_SETTINGS_MODULE'] = 'DangDang.settings'

if __name__ == '__main__':
    send_mail(
    '11231',
    '312312',
    '*****@*****.**',
    ['*****@*****.**'],
    )
Example #46
0
def send_mail(subject, message, to):
    django_mail.send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [to])
Example #47
0
def register(request):
    """
    Handle the registration form.

    On a GET, display the form.
    On a POST, register the new user, set up their profile, and log them in
    (logging the current user out if necessary).
    """

    if request.method == 'GET':
        form = RegistrationForm(auto_id=True)
        return render_to_response('gcd/accounts/register.html',
          { 'form' : form },
          context_instance=RequestContext(request))
        
    errors = []
    form = RegistrationForm(request.POST)
    if not form.is_valid():
        return render_to_response('gcd/accounts/register.html',
                                  { 'form': form },
                                  context_instance=RequestContext(request))

    cd = form.cleaned_data
    email_users = User.objects.filter(email=cd['email'])
    if email_users.count():
        return handle_existing_account(request, email_users)

    # To make a unique username, take the first 20 characters before the "@"
    # in the email address, and tack on a number if that username is already
    # in use.  These usernames will not ever be shown except by accident
    # or possibly in corners of the admin UI that insist on displaying them,
    # but only admins and possibly editors will have access to that if we
    # use it at all.  20 characters just to give plenty of room in 30-character
    # username field for a disambiguating number, and maybe some other stuff
    # if we ever need to change this algorithm.

    # NOTE: We just go ahead and attempt to insert the user and then catch
    # the integrity error because any other strategy involves race conditions
    # so we'd have to catch it anyway.  We limit this to 10 tries to prevent
    # some other condition that raises the exception from trapping us in
    # an infinite loop.

    username_base = re.sub('@.*$', '', cd['email'])[:20]
    user_count = User.objects.count()
    new_user = None
    last_delta = 10
    for delta in range(1, last_delta):
        username = '******' % (username_base, user_count + delta)
        try:
            new_user = User.objects.create_user(username,
                                                cd['email'],
                                                cd['password'])
            break
        except IntegrityError:
            if delta == last_delta:
                raise

    if new_user is None:
        return render_error(request, 
          ('Could not create unique internal account name.  This is a very '
           'unlikely error, and it will probably go away if you try to '
           'register again.  We apologize for the inconvenience.  If it '
           'does not go away, please email <a href="mailto:%s">%s</a>.') %
          (settings.EMAIL_CONTACT, settings.EMAIL_CONTACT),is_safe=True)

    new_user.first_name = cd['first_name']
    new_user.last_name = cd['last_name']
    new_user.is_active = False
    new_user.save()

    new_user.groups.add(*Group.objects.filter(name='indexer'))

    salt = sha.new(str(random())).hexdigest()[:5]
    key = sha.new(salt + new_user.email).hexdigest()
    expires = date.today() + timedelta(settings.REGISTRATION_EXPIRATION_DELTA)
    indexer = Indexer(is_new=True,
                      max_reservations=settings.RESERVE_MAX_INITIAL,
                      max_ongoing=settings.RESERVE_MAX_ONGOING_INITIAL,
                      country=cd['country'],
                      interests=cd['interests'],
                      registration_key=key,
                      registration_expires=expires,
                      user=new_user)
    indexer.save()

    if cd['languages']:
        indexer.languages.add(*cd['languages'])

    email_body = """
Hello from the %s!

  We've received a request for an account using this email
address.  If you did indeed register an account with us,
please confirm your account by going to:

%s

within the next %d days.

  If you did not register for an account, then someone else is trying to
use your email address.  In that case, simply do not confirm the account
and it will expire after %d days.

thanks,
-the %s team
%s
""" % (settings.SITE_NAME,
       settings.SITE_URL.rstrip('/') +
         urlresolvers.reverse('confirm', kwargs={ 'key': key }),
       settings.REGISTRATION_EXPIRATION_DELTA,
       settings.REGISTRATION_EXPIRATION_DELTA,
       settings.SITE_NAME,
       settings.SITE_URL)

    send_mail(from_email=settings.EMAIL_NEW_ACCOUNTS_FROM,
              recipient_list=[new_user.email],
              subject='GCD new account confirmation',
              message=email_body,
              fail_silently=(not settings.BETA))

    return HttpResponseRedirect(urlresolvers.reverse('confirm_instructions'))
Example #48
0
import os
from django.core.mail import send_mail

os.environ['DJANGO_SETTINGS_MODULE'] = 'jing.settings'

if __name__ == '__main__':

    send_mail(
        '来自www.liujiangblog.com的测试邮件',
        '欢迎访问www.liujiangblog.com,这里是刘江的博客和教程站点,本站专注于Python、Django和机器学习技术的分享!',
        '*****@*****.**',
        ['*****@*****.**'],
    )
# 发送HTML格式的邮件
import os
from django.core.mail import EmailMultiAlternatives

os.environ['DJANGO_SETTINGS_MODULE'] = 'jing.settings'

if __name__ == '__main__':

    subject, from_email, to = '来自www.liujiangblog.com的测试邮件', '*****@*****.**', '*****@*****.**'
    text_content = '欢迎访问www.liujiangblog.com,这里是刘江的博客和教程站点,专注于Python和Django技术的分享!'
    html_content = '<p>欢迎访问<a href="http://www.liujiangblog.com" target=blank>www.liujiangblog.com</a>,这里是刘江的博客和教程站点,本站专注于Python、Django和机器学习技术的分享!</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

# 版本三:
from django.conf import settings
Example #49
0
def make_order(request):
    GroupOrder.close_deadline_passed_grouper_order()

    if request.method == "GET":
        return render(
            request, "order.haml", {
                "form":
                OrderForm(),
                "default_components":
                Component.objects.filter(in_default_pack=True, available=True),
                "other_components":
                Component.objects.filter(in_default_pack=False,
                                         available=True),
            })

    assert request.method == "POST"

    form = OrderForm(request.POST)

    print request.POST

    if not form.is_valid():
        print form.errors
        return render(
            request, "order.haml", {
                "form":
                form,
                "default_components":
                Component.objects.filter(in_default_pack=True, available=True),
                "other_components":
                Component.objects.filter(in_default_pack=False,
                                         available=True),
            })

    with transaction.atomic():
        order = form.save()

        for component in Component.objects.filter(available=True):
            if form.cleaned_data["component_%d_number" % component.id] > 0:
                ComponentOrder.objects.create(
                    order=order,
                    component=component,
                    number=form.cleaned_data["component_%d_number" %
                                             component.id])

        send_mail(
            _(u'[Neutrinet] Order #%s for one or more Internet Cube') %
            order.id,
            get_template('email.txt').render(Context({"order": order})),
            '*****@*****.**',
            [order.email],
            fail_silently=False,
        )

        send_mail(
            u'[cube order] Order #%s by %s %s (%s)' %
            (order.id, order.first_name, order.last_name,
             order.nick if order.nick else "no nick"),
            get_template('admin_email.txt').render(Context({"order": order})),
            '*****@*****.**',
            ['*****@*****.**'],
            fail_silently=False,
        )

    return HttpResponseRedirect(reverse("success"))
Example #50
0
 def email_user(self, subject, message, from_email=None):
     "Sends an e-mail to this User."
     send_mail(subject, message, from_email, [self.email])
Example #51
0
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.template.loader import render_to_string

User = get_user_model()

sender = '*****@*****.**'

test_user = User.objects.get(email='*****@*****.**')

email_subject = render_to_string('Email_notification_newFeatures_subject.txt')
email_body = render_to_string('Email_notification.html', {'user': test_user})
if send_mail(email_subject,
             email_body,
             sender, [test_user.email],
             fail_silently=False):
    print 'email sent'
else:
    print 'email sending crashed'
def send_email_alert(report, email):
    subject = '[Team 9]'
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [email]
    send_mail(subject, report, email_from, recipient_list)
Example #53
0
def import_teetime_recurring_queue():
    re_teetime = RecurringTeetime.objects.all()
    if not re_teetime:
        return

    email_data = []
    for rt in re_teetime:
        tz = timezone(country_timezones(rt.golfcourse.country.short_name)[0])
        now = datetime.datetime.utcnow()
        current_tz = datetime.datetime.fromtimestamp(now.timestamp(), tz)
        #### Check next date: publish: move date, recurring: move back and plus 7
        ### Get the max date of teetime exists
        max_date = TeeTime.objects.filter(golfcourse=rt.golfcourse).aggregate(
            Max('date'))['date__max']
        if not max_date:
            continue
        if not rt.publish_period and not rt.recurring_freq:
            continue
        if (current_tz.date() +
                datetime.timedelta(days=rt.publish_period)) < max_date:
            continue
        list_date = []
        for i in range(1, rt.recurring_freq + 1):
            next_date = max_date + datetime.timedelta(days=i)
            get_date = next_date - datetime.timedelta(days=7)
            tt = TeeTime.objects.filter(golfcourse=rt.golfcourse,
                                        date=get_date)
            if tt.exists():
                list_date.append(next_date)
                for t in tt:
                    teetime_price = TeeTimePrice.objects.filter(teetime=t)
                    t.date = next_date
                    t.is_hold = False
                    t.is_block = False
                    t.is_booked = False
                    t.is_request = False
                    t.id = None
                    t.save()
                    for tp in teetime_price:
                        tp.teetime = t
                        tp.id = None
                        tp.is_publish = True
                        tp.save()
        if list_date:
            data = {rt.golfcourse.name: list_date}
            email_data.append(data)

    # send_email(email_data)
    if not email_data:
        return

    template = "Import {0} at [{1}]"
    message = ""
    for d in email_data:
        for k, v in d.items():
            message += template.format(k, ', '.join(map(str, v))) + "\n"

    if ADMIN_EMAIL_RECIPIENT:
        send_mail('Import teetime date {} - env {}'.format(
            datetime.date.today(), CURRENT_ENV),
                  message,
                  'GolfConnect24 <*****@*****.**>',
                  ADMIN_EMAIL_RECIPIENT,
                  fail_silently=True)
def analyze(request):
    djtext = request.POST.get('text', 'default')
    removepunc = request.POST.get('removepunc', 'of')
    allcaps = request.POST.get('allcaps', 'of')
    newlineremove = request.POST.get('lineremo', 'of')
    extraspaceremover = request.POST.get('exspre', 'of')
    print(djtext)
    # print(djtext)
    print(removepunc)
    if removepunc == "on":
        punctuations = '''!()-[]{};:'+\",<>./?@#$%^&*|=_~'''
        analyzed = ""
        for char in djtext:
            if char not in punctuations:
                analyzed = analyzed + char
                params = {'purpose': 'removepunc', 'analyzed_text': analyzed}
        djtext = analyzed
        # return render(request, 'analyze.html', params)

    if allcaps == "on":
        analyzed = ""
        for char in djtext:
            analyzed = analyzed + char.upper()

        params = {
            'purpose': 'changes lower case to upper case',
            'analyzed_text': analyzed
        }
        djtext = analyzed
        # return render(request, 'analyze.html', params)

    if newlineremove == "on":
        analyzed = ""
        for char in djtext:
            if char != "\n" and char != "\r":
                analyzed = analyzed + char

        params = {
            'purpose': 'removed new lines buddy',
            'analyzed_text': analyzed
        }
        djtext = analyzed
        # return render(request, 'analyze.html', params)

    if extraspaceremover == "on":
        analyzed = ""
        for index, char in enumerate(djtext):
            if djtext[index] == " " and djtext[index + 1] == " ":
                pass
            else:
                analyzed = analyzed + char

        params = {
            'purpose': 'removed extra white spaces buddy',
            'analyzed_text': analyzed
        }
        if removepunc == "of" and allcaps == "of" and extraspaceremover == "of" and newlineremove == "of":
            return HttpResponse("Error bhai! error alltime error")
            djtext = analyze
            # return render(request, 'analyze.html', params)
    # else:
    #     return HttpResponse("Please check the checkbox to get expected output")

    return render(request, 'analyze.html', params)

    send_mail(
        'This is the subject',
        'Hello mister human how are you',
        '*****@*****.**',
        ['*****@*****.**'],
        fail_silently=False,
    )
Example #55
0
def send_email_on_reject(house, guest, owner, owner_email, reservation_id):
    send_mail('Ответ по брони на AKV',
              f'Здравствуйте, {owner}. Вашу бронь для дома {house} отклонили',
              'webmaster@localhost', [owner_email],
              fail_silently=False)
    return None
Example #56
0
 def send_email(self):
     send_mail('[GoDjango Feedback Form]',
               self.cleaned_data['body'],
               self.cleaned_data['email'], ['*****@*****.**'],
               fail_silently=False)
Example #57
0
def get_title(self, referer_id):
    """Get the HTML title for a page, trying again if failures occur.

    Idea here is that somebody will create a new page that embeds one of our
    maps. As soon as they do, we'll get an HTTP referer sent to us, which is
    great. Unfortunately, in many cases, the HTTP referer we receive is that of
    an in progress page or similar, NOT the page that's actually live. Thus,
    what we do is try the URL over and over, until we find success.

    If a title is found, the admins are notified.

    If not, the item is deleted (this is OK, however, b/c it'll be recreated if
    it should have existed).
    """
    # Set the exponential back off in case we need it, starting at 15 minutes,
    # then 30, 60, 120...
    countdown = 15 * 60 * (2**self.request.retries)
    retried_exceeded = (self.request.retries >= self.max_retries)

    referer = Referer.objects.get(pk=referer_id)
    if blacklisted_url(referer.url):
        return

    try:
        r = requests.get(
            referer.url,
            headers={'User-Agent': "CourtListener"},
            verify=False,  # Integrity of a referer's referent is not important.
        )
    except MissingSchema:
        return

    try:
        r.raise_for_status()
    except HTTPError as exc:
        if retried_exceeded:
            # We're not wanted here. Maybe we'll have better luck another time.
            return
        raise self.retry(exc=exc, countdown=countdown)

    html_tree = html.fromstring(r.text)
    try:
        title = getattr(html_tree.xpath('//title')[0], 'text', '')
        if title is not None:
            title = title.strip()
    except IndexError:
        title = ''

    if title:
        referer.page_title = trunc(
            title,
            referer._meta.get_field('page_title').max_length,
        )
        referer.save()

        if new_title_for_viz(referer):
            # Only send the email if we haven't seen this page title before for
            # this visualization.
            email = emails['referer_detected']
            email_body = email['body'] % (
                referer.url, referer.page_title,
                reverse('admin:visualizations_referer_change',
                        args=(referer.pk, )))
            send_mail(email['subject'], email_body, email['from'], email['to'])
    else:
        try:
            # Create an exception to catch.
            raise Exception("Couldn't get title from HTML")
        except Exception as exc:
            if retried_exceeded:
                # We couldn't get the title. Let it go.
                return
            raise self.retry(exc=exc, countdown=countdown)
Example #58
0
def autoreg(**kwargs):
    connection = kwargs['connection']
    progress = kwargs['sender']
    autoreg_scripts = get_scripts()
    if progress.script.slug in progress.script.slug in autoreg_scripts:
        connection.contact = Contact.objects.create(name='Anonymous User')
        connection.save()
        session = ScriptSession.objects.filter(script=progress.script, connection=connection).order_by('-end_time')[0]
        script = progress.script
        reporter_group_poll = script.steps.get(order=1).poll
        reporter_reporting_location_poll = script.steps.get(order=2).poll
        reporter_colline_poll = script.steps.get(order=3).poll
        reporter_name_poll = script.steps.get(order=5).poll
        reporter_age_poll = script.steps.get(order=6).poll
        reporter_gender_poll = script.steps.get(order=7).poll
        contact = connection.contact
        word_dict=dict(AutoregGroupRules.objects.exclude(values=None).values_list('group__name','values'))
        name = find_best_response(session, reporter_name_poll)
        if name:
            contact.name = name[:100]

        contact.reporting_location = find_best_response(session, reporter_reporting_location_poll)

        age = find_best_response(session, reporter_age_poll)
        if age and age < 100:
            contact.birthdate = datetime.datetime.now() - datetime.timedelta(days=(365 * int(age)))

        gresps = session.responses.filter(response__poll=reporter_gender_poll, response__has_errors=False).order_by('-response__date')
        if gresps.count():
            gender = gresps[0].response
            if gender.categories.filter(category__name='male').count():
                contact.gender = 'M'
            elif gender.categories.filter(category__name='female').exists():
                contact.gender = 'F'

        colline = find_best_response(session, reporter_colline_poll)
        if colline:
            contact.colline = colline
        group_to_match = find_best_response(session, reporter_group_poll)
        gr_matched = False

        #to avoid an attempt to None.split()
        if group_to_match:
            try:
                for group_pk, word_list in word_dict.items():
                    for word in word_list.split(","):
                        if word in group_to_match.split():
                            try:
                                contact.groups.add(Group.objects.get(name=group_pk))
                            except (ValueError, Group.DoesNotExist):
                                try:
                                    contact.groups.add(Group.objects.get(pk=group_pk))
                                except (ValueError, Group.DoesNotExist):
                                    pass
                            gr_matched = True
            except AssertionError:
                pass
        default_group = None
        if progress.language:
            contact.language = progress.language
        if Group.objects.filter(name='Other uReporters').exists():
            default_group = Group.objects.get(name='Other uReporters')
        if group_to_match and not gr_matched:

            for g in re.findall(r'\w+', group_to_match):
                if g:
                    excluded = AutoregGroupRules.objects.filter(closed=True).values('group__pk')
                    group = find_closest_match(str(g), Group.objects.exclude(pk__in=excluded))
                    if group:
                        contact.groups.add(group)
                        break

            if default_group:
                contact.groups.add(default_group)

        if not contact.name:
            contact.name = 'Anonymous User'
        contact.save()

        total_ureporters = Contact.objects.exclude(
            connection__identity__in=Blacklist.objects.values_list('connection__identity')).count()
        if total_ureporters % getattr(settings, 'USER_MILESTONE', 500) == 0:
            recipients = getattr(settings, 'ADMINS', None)
            if recipients:
                recipients = [email for name, email in recipients]
            mgr = getattr(settings, 'MANAGERS', None)
            if mgr:
                for email in mgr:
                    recipients.append(email)
            send_mail("UReport now %d voices strong!" % total_ureporters,
                      "%s (%s) was the %dth member to finish the sign-up.  Let's welcome them!" % (
                          contact.name, connection.identity, total_ureporters), '*****@*****.**', recipients,
                      fail_silently=True)
Example #59
0
def reset(request, uuid=None):
    """
    Resets the password for the given reset id.
    """
    # If the uuid argument is not available, we have to render the reset form.
    if not uuid:
        # Check if the ResetRequestForm form has been submitted.
        if request.method == "POST":
            # If so, bind the reset form to HTTP POST values.
            form = ResetRequestForm(request.POST)

            # Check if the form has validated successfully.
            if form.is_valid():
                # Create a new ResetRequest instance for the User.
                user = User.objects.get(username=form.cleaned_data['username'],
                                        email=form.cleaned_data['email'])
                new_object = ResetRequest(user=user)
                new_object.save()

                # Render reset email template with correct values.
                data = {
                    'firstname':
                    user.first_name,
                    'lastname':
                    user.last_name,
                    'shortname':
                    user.username,
                    'confirmation_url':
                    '{0}/accounts/reset/{1}/'.format(DJANGO_URL,
                                                     new_object.uuid)
                }
                email = render_to_string('accounts/reset_email.html', data)

                try:
                    # Send out reset email to the given email address.
                    send_mail(
                        _('Please confirm your ELRI password reset request'),
                        email,
                        EMAIL_ADDRESSES['elri-no-reply'], [user.email],
                        fail_silently=False)

                except SMTPException:
                    # If the email could not be sent successfully, we simply
                    # redirect the user to the front page.
                    return redirect('metashare.views.frontpage')

                # Add a message to the user after successful creation.
                messages.success(request,
                  _("We have received your password reset request and sent you an " \
                    "email with further instructions."))

                # Redirect the user to the front page.
                return redirect('metashare.views.frontpage')

        # Otherwise, create an empty ResetRequestForm instance.
        else:
            form = ResetRequestForm()

        dictionary = {'title': _('Reset user account'), 'form': form}
        return render_to_response('accounts/reset_account.html',
                                  dictionary,
                                  context_instance=RequestContext(request))

    # If the uuid is given, we have to process the corresponding ResetRequest.
    # We lookup the ResetRequest instance and create a new, random password.
    user_reset = get_object_or_404(ResetRequest, uuid=uuid)
    random_password = User.objects.make_random_password()

    # Then we update the corresponding User instance with the new password.
    user = user_reset.user
    user.set_password(random_password)
    user.save()

    # Delete reset request instance.
    user_reset.delete()

    # Render re-activation email template with correct values.
    data = {
        'firstname': user_reset.user.first_name,
        'lastname': user.last_name,
        'shortname': user.username,
        'random_password': random_password
    }
    email = render_to_string('accounts/reactivation_email.html', data)

    try:
        # Send out re-activation email to the given email address.
        send_mail(_('Your ELRI user account has been re-activated'),
                  email,
                  EMAIL_ADDRESSES['elri-no-reply'], [user.email],
                  fail_silently=False)

    except SMTPException:
        # If the email could not be sent successfully, tell the user about it.
        messages.error(request,
          _("There was an error sending out the activation email " \
            "for your user account. Please contact the administrator at %s.")
          % (User.objects.filter(is_superuser=True) \
             .values_list('email', flat=True)[0],))
        # Redirect the user to the front page.
        return redirect('metashare.views.frontpage')

    # Add a message to the user after successful creation.
    messages.success(request,
      _("We have re-activated your user account and sent you an email with " \
        "your personal password which allows you to login to the website."))

    # Redirect the user to the front page.
    return redirect('metashare.views.frontpage')
Example #60
0
def crear_asistencia_CE(request):
    ############################################################################
    #Agregar validacion de rol, si el rol no corresponde, redirigirlo al home o
    # a pagina que indique acceso denegado se traen los roles que tiene asignado el usuario
    roles = KerSocioRol.objects.filter(socio=request.user).order_by('rol')
    allow = False
    for rol in roles:
        if rol.rol.tipo_rol == 'Asistencia':
            allow = True
    if not allow:
        return HttpResponseRedirect(reverse('home'))
    ############################################################################
    asistenciaenc_form = AsistenciaEncFormCE()
    # messages.info(request, 'Funcionando!')
    print('Funcionando!')
    if KerSocioRol.objects.filter(socio=request.user).exists():
        if request.method == 'POST':
            # leer el archivo con los ruts que asistieron y guardarlo en variable CSV
            for upfile in request.FILES.getlist('archivo'):
                csv_reader = csv.reader(
                    upfile.read().decode('utf-8').splitlines())
                asistenciaenc_form = AsistenciaEncFormCE(
                    request.POST, request.FILES)
                if asistenciaenc_form.is_valid():
                    asistencia = asistenciaenc_form.save()
                    # Usar el usuario conectado para grabar el encabezado
                    asistencia.usuario = request.user.username
                    asistencia.save()
                    # Guardar temporalmente los rut del csv a una tabla
                    for line in csv_reader:
                        rut = str.strip(line[0].replace('\n',
                                                        '').replace('\r', ''))
                        asistente = Asistentes()
                        asistente.folio = asistencia.pk
                        asistente.rut_socio = rut
                        asistente.save()
                    # Traer todos los socios activos para verificar la asistencia
                    socios_activos = User.objects.filter(
                        estado_socio='Vigente')
                    # Crear un registros para cada usuario activo en el detalle de la asistencia
                    for socio in socios_activos:
                        asistencia_det = AsistenciaDet()
                        asistencia_det.asistenciaenc = asistencia
                        asistencia_det.fec_evento = asistencia.fec_evento
                        asistencia_det.rut_socio = socio.username
                        asistencia_det.email = socio.email
                        asistencia_det.nombre = socio.first_name
                        asistencia_det.apellido = socio.last_name
                        asistencia_det.save()
                    # Traer todos los registros creados en el detalle de esta asistencia
                    detalle_asis = AsistenciaDet.objects.filter(
                        asistenciaenc=asistencia)
                    # print('marcando asistencia')
                    for det in detalle_asis:
                        # Traer los asistentes de la tabla temporal
                        asistentes = Asistentes.objects.all()
                        for line in asistentes:
                            # buscar el registro del detalle del rut del CSV
                            if det.rut_socio == line.rut_socio:
                                detalle = AsistenciaDet.objects.get(
                                    asistenciaenc=asistencia,
                                    rut_socio=line.rut_socio)
                                # messages.info(request, 'Asistio')
                                # Si el indicador es verdadero (hizo match) se cuenta como
                                # asistencia y se marca con Asistio, de lo contrario queda
                                # como venia (No Asistio) y
                                # se actualiza el registro con el indicador de asistencia
                                detalle.est_asistencia = 'Asistio'
                                detalle.save()
                    # Despues de terminar el ciclo se calculan los totales del
                    # encabezado y se actualiza el encabezado
                    Asistentes.objects.all().delete()
                    print('calculando totaltes')
                    asistencia.cant_total = detalle_asis.count()
                    asistencia.cant_asistencias = detalle_asis.filter(
                        asistenciaenc=asistencia,
                        est_asistencia='Asistio').count()
                    asistencia.cant_ausentes = detalle_asis.filter(
                        asistenciaenc=asistencia,
                        est_asistencia='No Asistio').count()
                    asistencia.save()
                    #Mandar correo a los inasistentes
                    inasistentes = AsistenciaDet.objects.filter(
                        asistenciaenc=asistencia, est_asistencia='No Asistio')
                    # Plantilla de mensaje al sindicato sin los notificados
                    notificacion_al_sindicato = 'Estimados administradores del Sindicato:\n\nSe ha notificado la inasistencia a: %s - %s a los siguientes socios\n\n' % (
                        asistencia.tipo_evento,
                        asistencia.fec_evento.strftime("%d/%m/%Y"))
                    # Plantilla de notificacion al socio
                    mensaje = 'Estimado(a): Socio(a)\n\nMediante este correo se le notifica su inasistencia a %s - %s\n\nPuede presentar justificativo respondiendo y adjunto lo correspondiente a este correo\n\nSinceramente, Sindicato Unificado Metro' % (
                        asistencia.tipo_evento,
                        asistencia.fec_evento.strftime("%d/%m/%Y"))
                    # Se recorre a los inasistentes para rellenar el mensaje de correo al sindicato
                    for inasistente in inasistentes:
                        notificacion_al_sindicato = notificacion_al_sindicato + '%s %s - %s\n' % (
                            inasistente.nombre, inasistente.apellido,
                            inasistente.email)
                    # Enviar notificacion a los inasistentes
                    # send_mail(
                    #     'Notificacion de Inasistencia a %s - %s'%(asistencia.tipo_evento,asistencia.fec_evento),
                    #     mensaje,
                    #     '*****@*****.**',
                    #     [ina.email for ina in inasistentes],
                    #     fail_silently=True,
                    # )
                    # Se recorren los inasistentes y se marca la notificacion
                    for inasistente in inasistentes:
                        inasistente.est_notificacion = 'Notificado'
                        inasistente.save()
                    #Enviar correo de notificacion al sindicato indicando lo informado
                    send_mail(
                        'Generacion de Asistencia - %s - %s' %
                        (asistencia.tipo_evento,
                         asistencia.fec_evento.strftime("%d/%m/%Y")),
                        notificacion_al_sindicato, '*****@*****.**', [
                            '*****@*****.**',
                        ])
                    messages.success(request, 'Proceso Terminado!')
            context = {
                'asistenciaenc_form': asistenciaenc_form,
                'roles': roles,
            }
            print('terminando proceso')
            return render(request, 'asistencias/crear_asistencia.html',
                          context)
        else:
            asistenciaenc_form = AsistenciaEncFormCE()
        context = {
            'asistenciaenc_form': asistenciaenc_form,
            'roles': roles,
        }
        return render(request, 'asistencias/crear_asistencia_CE.html', context)
    else:
        return render(request, 'index.html', context)