Exemple #1
0
def email_message(email_subject, email_body, chapter):
    message = EmailMessage()
    message.subject = email_subject
    message.body = email_body
    message.from_name = "myRobogals"
    message.from_address = "*****@*****.**"
    message.reply_address = "*****@*****.**"
    message.sender = User.objects.get(username='******')
    message.html = True
    message.email_type = 0

    # Message is set to WAIT mode
    message.status = -1
    message.save()

    # Creates a list of all users to notify
    if chapter.notify_list != None:
        users_to_notify = chapter.notify_list.users.all()

        # Email to all users that need to be notified
        for user in users_to_notify:
            recipient = EmailRecipient()
            recipient.message = message
            recipient.user = user
            recipient.to_name = user.get_full_name()
            recipient.to_address = user.email
            recipient.save()
            message.status = 0
            message.save()
Exemple #2
0
def genandsendpw(user, welcomeemail, chapter):
    plaintext_password = User.objects.make_random_password(6)
    user.set_password(plaintext_password)
    user.save()

    message = EmailMessage()
    message.subject = welcomeemail['subject']
    try:
        message.body = welcomeemail['body'].format(
            chapter=chapter,
            user=user,
            plaintext_password=plaintext_password)
    except Exception:
        raise RgGenAndSendPwException('Email body contains invalid fields')
    message.from_address = '*****@*****.**'
    message.reply_address = '*****@*****.**'
    message.from_name = chapter.name
    message.sender = User.objects.get(username='******')
    message.html = welcomeemail['html']
    message.status = -1
    message.save()
    recipient = EmailRecipient()
    recipient.message = message
    recipient.user = user
    recipient.to_name = user.get_full_name()
    recipient.to_address = user.email
    recipient.save()
    message.status = 0
    message.save()
Exemple #3
0
 def send_mail(self,
               subject_template_name,
               email_template_name,
               context,
               from_email,
               to_email,
               html_email_template_name=None):
     body = loader.render_to_string(email_template_name, context)
     message = EmailMessage()
     message.subject = 'Password reset'
     message.body = body
     message.from_address = '*****@*****.**'
     message.reply_address = '*****@*****.**'
     message.from_name = context['user'].chapter.name
     message.sender = User.objects.get(username='******')
     message.html = False
     message.status = -1
     message.save()
     recipient = EmailRecipient()
     recipient.message = message
     recipient.user = context['user']
     recipient.to_name = context['user'].get_full_name()
     recipient.to_address = to_email
     recipient.save()
     message.status = 0
     message.save()
Exemple #4
0
def cancelvisit(request, visit_id):
    if not request.user.is_staff:
        raise Http404
    chapter = request.user.chapter
    v = get_object_or_404(SchoolVisit, pk=visit_id)
    if (v.chapter != chapter) and not request.user.is_superuser:
        raise Http404
    if request.method == 'POST':
        cancelform = CancelForm(request.POST, user=request.user, visit=v)
        if cancelform.is_valid():
            data = cancelform.cleaned_data
            message = EmailMessage()
            message.subject = data['subject']
            message.body = data['body']
            message.from_address = request.user.email
            message.reply_address = request.user.email
            message.sender = request.user
            message.html = True
            message.from_name = chapter.name
            message.scheduled = False

            # Don't send it yet until the recipient list is done
            message.status = -1
            # Save to database so we get a value for the primary key,
            # which we need for entering the recipient entries
            message.save()

            # Send to everyone who has been invited
            id_list = EventAttendee.objects.filter(
                event=v.id, rsvp_status=2).values_list('user_id')
            users = User.objects.filter(id__in=id_list,
                                        is_active=True,
                                        email_reminder_optin=True)

            for one_user in users:
                recipient = EmailRecipient()
                recipient.message = message
                recipient.user = one_user
                recipient.to_name = one_user.get_full_name()
                recipient.to_address = one_user.email
                recipient.save()

            message.status = 0
            message.save()
            Event.objects.filter(id=v.id).delete()
            messages.success(request,
                             message=unicode(
                                 _("Visit cancelled successfully")))
            return HttpResponseRedirect('/teaching/list/')
    else:
        cancelform = CancelForm(None, user=request.user, visit=v)
    return render_to_response('visit_cancel.html', {
        'cancelform': cancelform,
        'visit_id': visit_id
    },
                              context_instance=RequestContext(request))
Exemple #5
0
def welcome_email(request, chapter, u):
    message = EmailMessage()

    try:
        message.subject = chapter.welcome_email_subject.format(
            chapter=chapter,
            user=u,
            plaintext_password=request.POST['password1'])
    except Exception:
        message.subject = chapter.welcome_email_subject

    try:
        message.body = chapter.welcome_email_msg.format(
            chapter=chapter,
            user=u,
            plaintext_password=request.POST['password1'])
    except Exception:
        message.body = chapter.welcome_email_msg

    # Setting defaults
    message.from_address = '*****@*****.**'
    message.reply_address = '*****@*****.**'
    message.from_name = chapter.name
    message.sender = User.objects.get(username='******')
    message.html = chapter.welcome_email_html

    # Setting message to -1 in the DB shows that the message is in WAIT mode
    message.status = -1
    message.save()

    # Prepares message for sending
    recipient = EmailRecipient()
    recipient.message = message
    recipient.user = u
    recipient.to_name = u.get_full_name()
    recipient.to_address = u.email
    recipient.save()

    # Change message to PENIDNG mode, which waits for server to send
    message.status = 0
    message.save()
Exemple #6
0
def check_default_pass():
    users = User.objects.all()
    for u in users:
        if check_password("newrg123", u.password):
            message = EmailMessage()
            message.body = "Dear " + u.first_name + ",\n\nYou are recieving this automated email because your myRobogals account is still set to use the default password. This is a security risk and exposes your myRobogals account to potentially being used by others.\n\nPlease login at http://my.robogals.org using the following credentials:\nUsername: "******"\nPassword: newrg123\n\nOnce you have logged in, please change your password.\n\nThankyou,\n\nmyRobogals password nagging bot :)"
            message.subject = "Warning: Account is using default password"
            message.from_address = "*****@*****.**"
            message.from_name = "myRobogals"
            message.reply_address = "*****@*****.**"
            message.html = False
            message.status = -1
            message.sender_id = 168
            message.save()
            recipient = EmailRecipient()
            recipient.message = message
            recipient.user = u
            recipient.to_name = u.get_full_name()
            recipient.to_address = u.email
            recipient.save()
            message.status = 0
            message.save()
Exemple #7
0
def send_email(email_subject, email_body, to_address):
    #Set up message fields
    message = EmailMessage()
    message.subject = email_subject
    message.body = email_body
    message.from_name = "myRobogals"
    message.from_address = "*****@*****.**"
    message.reply_address = "*****@*****.**"
    message.sender = User.objects.get(username='******')
    message.html = True
    message.email_type = 0

    #set message to WAIT
    message.status = -1
    message.save()

    #Set up recipient fields
    recipient = EmailRecipient()
    recipient.message = message
    recipient.to_address = to_address

    #Set message to PENDING, save and send
    message.status = 0
    message.save()
Exemple #8
0
def importcsv(filerows, welcomeemail, defaults, newsletter, user):
    columns = None
    subscribers_imported = 0
    most_recent_issue = newsletter.get_most_recent()
    if defaults['type']:
        defaults['subscriber_type_id'] = defaults['type'].pk
    countries = Country.objects.all()
    country_ids = []
    for country in countries:
        country_ids.append(country.pk)
    for row in filerows:
        try:
            # Get column names from first row
            if (columns == None):
                columns = row
                if 'email' not in columns:
                    raise RgImportCsvException('You must specify an email field')
                continue

            # Create new user
            newsubscriber = NewsletterSubscriber()

            # Process row
            i = 0
            send_most_recent = defaults['send_most_recent']
            send_email = False
            for cell in row:
                colname = columns[i]
                if colname == 'email':
                    stringval(colname, cell, newsubscriber, defaults)
                    if not email_re.match(newsubscriber.email):
                        raise SkipRowException
                    if NewsletterSubscriber.objects.filter(email=newsubscriber.email,
                                                           newsletter=newsletter).count() > 0:
                        raise SkipRowException  # This email address is already subscribed
                    if newsletter.pk == 1:
                        users_count = User.objects.filter(is_active=True, email=newsubscriber.email,
                                                          email_newsletter_optin=True).count()
                        if users_count > 0:
                            raise SkipRowException  # This email address is already subscribed by having User.email_newsletter_optin True
                    if newsletter.pk == 5:
                        users_count = User.objects.filter(is_active=True, email=newsubscriber.email,
                                                          email_careers_newsletter_AU_optin=True).count()
                        if users_count > 0:
                            raise SkipRowException  # This email address is already subscribed by having User.email_newsletter_optin True
                elif colname == 'first_name':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'last_name':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'company':
                    stringval(colname, cell, newsubscriber, defaults)
                elif colname == 'type':
                    types = SubscriberType.objects.all()
                    type_ids = []
                    for type in types:
                        type_ids.append(type.pk)
                    numval('subscriber_type_id', cell, newsubscriber, defaults, type_ids)
                elif colname == 'country':
                    if cell in country_ids:
                        stringval('country_id', cell, newsubscriber, defaults)
                    else:
                        newsubscriber.country = defaults['country']
                elif colname == 'details_verified':
                    boolval(colname, cell, newsubscriber, defaults)
                elif colname == 'send_most_recent':
                    data = cell.strip()
                    if data == 'true':
                        send_most_recent = True
                    elif data == '1':
                        send_most_recent = True
                    elif data == 'yes':
                        send_most_recent = True
                    if data == 'false':
                        send_most_recent = False
                    elif data == '0':
                        send_most_recent = False
                    elif data == 'no':
                        send_most_recent = False
                elif colname == 'send_email':
                    data = cell.strip()
                    if data == 'true':
                        send_email = True
                    elif data == '1':
                        send_email = True
                    elif data == 'yes':
                        send_email = True
                else:
                    pass  # Unknown column, ignore
                # Increment column and do the loop again
                i += 1

            # Apply any unapplied defaults
            if 'type' not in columns:
                if 'subscriber_type_id' in defaults:
                    newsubscriber.subscriber_type_id = defaults['subscriber_type_id']
            if 'details_verified' not in columns:
                if 'details_verified' in defaults:
                    newsubscriber.details_verified = defaults['details_verified']
            if 'country' not in columns:
                if 'country' in defaults:
                    newsubscriber.country = defaults['country']

            # Set some other important attributes
            newsubscriber.newsletter = newsletter
            newsubscriber.subscribed_date = datetime.now()
            newsubscriber.active = True

            # And finally...
            newsubscriber.save()

            # Send welcome email, if applicable
            if (welcomeemail['importaction'] == '1' or (welcomeemail['importaction'] == '3' and send_email)):
                message = EmailMessage()
                message.subject = welcomeemail['subject']
                try:
                    message.body = welcomeemail['body'].format(
                        newsletter=newsletter,
                        subscriber=newsubscriber)
                except Exception:
                    newsubscriber.delete()
                    raise RgImportCsvException('Welcome email format is invalid')
                message.from_address = welcomeemail['from_address']
                message.reply_address = welcomeemail['reply_address']
                message.from_name = welcomeemail['from_name']
                message.sender = user
                message.html = welcomeemail['html']
                message.status = -1
                message.save()
                recipient = EmailRecipient()
                recipient.message = message
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()
                message.status = 0
                message.save()

            # Send most recent newsletter, if applicable
            if send_most_recent:
                recipient = EmailRecipient()
                recipient.message = most_recent_issue
                recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name
                recipient.to_address = newsubscriber.email
                recipient.save()

            # Increment counter
            subscribers_imported += 1
        except SkipRowException:
            continue  # Skip this row

    # Tell the most recent issue to send with new subscribers,
    # if applicable
    most_recent_issue.status = 0
    most_recent_issue.save()
    return subscribers_imported
Exemple #9
0
def api(request):
	if 'api' not in request.GET:
		return HttpResponse("-1")
	elif request.GET['api'] != API_SECRET:
		return HttpResponse("-1")
	elif 'action' in request.GET:
		try:
			n = Newsletter.objects.get(pk=request.GET['newsletter'])
		except Newsletter.DoesNotExist:
			return HttpResponse("-1")
		try:
			if request.GET['action'] == 'subscribe':
				email = unquote_plus(request.GET['email']).strip()
				try:
					validate_email(email)
				except ValidationError:
					valid_email = False
				else:
					valid_email = True
				if not valid_email:
					return HttpResponse("C")  # Invalid email
				c = NewsletterSubscriber.objects.filter(email=email, newsletter=n, active=True).count()
				if c != 0:
					return HttpResponse("B")  # Already subscribed
				if n.pk == 1:
					users_count = User.objects.filter(is_active=True, email=email, email_newsletter_optin=True).count()
					if users_count > 0:
						return HttpResponse("B")  # Already subscribed
				# They've tried to subscribe already, so resend confirmation email
				p = PendingNewsletterSubscriber.objects.filter(email=email, newsletter=n)
				if p:
					p = p[0]
				else:
					p = PendingNewsletterSubscriber()
					p.email = email
					p.uniqid = md5(SECRET_KEY + email + n.name).hexdigest()
					p.newsletter = n
					p.save()
				confirm_url = n.confirm_url + "pid=" + str(p.pk) + "&key=" + p.uniqid
				message = EmailMessage()
				message.subject = n.confirm_subject
				message.body = n.confirm_email.replace('{email}', email).replace('{url}', confirm_url)
				message.from_address = n.confirm_from_email
				message.from_name = n.confirm_from_name
				message.reply_address = n.confirm_from_email
				message.sender = n.confirm_from_user
				message.html = n.confirm_html
				# Don't send it yet until the recipient list is done
				message.status = -1
				# Save to database so we get a value for the primary key,
				# which we need for entering the recipient entries
				message.save()
				recipient = EmailRecipient()
				recipient.message = message
				recipient.to_name = ""
				recipient.to_address = email
				recipient.save()
				message.status = 0
				message.save()
				return HttpResponse("A")  # Success!
			elif request.GET['action'] == 'confirm':
				pid = unquote_plus(request.GET['id'])
				key = unquote_plus(request.GET['key'])
				try:
					p = PendingNewsletterSubscriber.objects.get(pk=pid, newsletter=n, uniqid=key)
				except PendingNewsletterSubscriber.DoesNotExist:
					return HttpResponse("B")
				try:
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						raise User.DoesNotExist
					try:
						u = User.objects.get(email=p.email)
					except User.MultipleObjectsReturned:
						# Subscribe the first user with this email address
						u = User.objects.filter(email=p.email)[0]
					# This user is already a Robogals member
					u.email_newsletter_optin = True
					u.save()
				except User.DoesNotExist:
					ns = NewsletterSubscriber()
					ns.newsletter = n
					ns.email = p.email
					ns.active = True
					ns.details_verified = False
					ns.save()
				PendingNewsletterSubscriber.objects.filter(email=p.email, newsletter=n).delete()
				return HttpResponse("A")
			elif request.GET['action'] == 'unsubscribe':
				email = unquote_plus(request.GET['email']).strip()
				try:
					ns = NewsletterSubscriber.objects.get(email=email, newsletter=n, active=True)
				except NewsletterSubscriber.DoesNotExist:
					# Not on the list. Perhaps subscribed as a Robogals member?
					if n.pk != 1:
						# Only do the user thing for The Amplifier (id = 1)
						return HttpResponse("B")  # Not subscribed
					try:
						for u in User.objects.filter(email=email):
							if u.email_newsletter_optin:
								u.email_newsletter_optin = False
								u.save()
								return HttpResponse("A")
						return HttpResponse("B")  # Not subscribed
					except User.DoesNotExist:
						return HttpResponse("B")  # Not subscribed
				ns.unsubscribed_date = datetime.now()
				ns.active = False
				ns.save()
				if n.pk == 1:
					for u in User.objects.filter(is_active=True, email=email, email_newsletter_optin=True):
						u.email_newsletter_optin = False
						u.save()
				return HttpResponse("A")
			else:
				return HttpResponse("-1")
		except KeyError:
			return HttpResponse("-1")
	else:
		return HttpResponse("-1")
Exemple #10
0
def writeemail(request):
	memberstatustypes = MemberStatusType.objects.all()
	if not request.user.is_staff:
		raise Http404
	if request.method == 'POST':
		typesel = request.POST['type']
		schedsel = request.POST['scheduling']
		statussel = request.POST['status']
		
		if 'step' in request.POST:
			if request.POST['step'] == '1':
				emailform = WriteEmailForm(request.POST, user=request.user)
				request.session['emailid'] = datetime.utcnow().strftime('%y%m%d%H%M%S')
				request.session['emailform'] = emailform
			elif request.POST['step'] == '2':
				if ('emailform' not in request.session) or ('emailid' not in request.session):
					if 'emailform' in request.session:
						del request.session['emailform']
					if 'emailid' in request.session:
						del request.session['emailid']
					raise Http404
				if request.session['emailid'] != request.POST['emailid']:
					raise Http404
				warning = False
				msg = ''
				maxfilesize = 10
				maxfilesetting = MessagesSettings.objects.filter(key='maxuploadfilesize')
				if maxfilesetting:
					maxfilesize = int(maxfilesetting[0].value)
				for f in request.FILES.getlist('upload_files'):
					if (f.name.__len__() > 70):
						msg += '<br>File name: "' + f.name + '" is longer than 70 characters'
						warning = True
					if (f.size > maxfilesize * 1024*1024):
						msg += '<br>File: "' + f.name + '" is larger than ' + str(maxfilesize) + ' MB'
						warning = True
				if warning:
					del request.session['emailform']
					del request.session['emailid']
					request.user.message_set.create(message=unicode(_('- Can not upload files. Reason(s): %s' % msg)))
					return HttpResponseRedirect('/messages/email/write/')
				emailform = request.session['emailform']
				del request.session['emailform']
				del request.session['emailid']
			else:
				raise Http404
		else:
			raise Http404
		if emailform.is_valid():
			data = emailform.cleaned_data
			if request.POST['step'] == '2':
				message = EmailMessage()
				message.subject = data['subject']
				if data['header_list']:
					hl = data['header_list']
					message.body = hl.upper_body + data['body'] + hl.lower_body
				else:
					message.body = data['body']
				message.from_address = request.user.email
				message.reply_address = request.user.email
				message.sender = request.user
				message.html = True

				if request.POST['scheduling'] == '1':
					message.scheduled = True
					message.scheduled_date = datetime.combine(data['schedule_date'], data['schedule_time'])
					try:
						message.scheduled_date_type = int(data['schedule_zone'])
					except Exception:
						message.scheduled_date_type = 1
				else:
					message.scheduled = False

				if request.POST['type'] == '4':
					n = data['newsletters']
					message.from_name = n.from_name
					message.from_address = n.from_email
					message.reply_address = n.from_email
					message.sender = n.from_user
				else:
					message.content_subtype = "html"
					if int(data['from_type']) == 0:
						message.from_name = "Robogals"
					elif int(data['from_type']) == 1:
						message.from_name = request.user.chapter.name
					else:
						message.from_name = request.user.get_full_name()
					
				# Don't send it yet until the recipient list is done
				message.status = -1
				# Save to database so we get a value for the primary key,
				# which we need for entering the recipient entries
				message.save()

			if request.POST['type'] == '1':
				if request.user.is_superuser:
					# "Email all members worldwide" feature disabled Nov 2010 - too much potential for abuse.
					# Can be re-enabled by uncommenting the following line, commenting the exception,
					# and removing the disabled tag from the relevant radio button in email_write.html
					#users = User.objects.filter(chapter__in=data['chapters'], is_active=True, email_chapter_optin=True)
					raise Exception
				else:
					users = User.objects.filter(chapter=request.user.chapter, is_active=True, email_chapter_optin=True).exclude(email='')
			elif request.POST['type'] == '2':
				if request.user.is_superuser:
					users = User.objects.filter(chapter__in=data['chapters_exec'], is_active=True, is_staff=True).exclude(email='')
				else:
					users = User.objects.filter(chapter=request.user.chapter, is_active=True, is_staff=True).exclude(email='')
			elif request.POST['type'] == '5':
				ul = data['list']
				users = ul.users.all().exclude(email='')
			elif request.POST['type'] == '4':
				if request.user.is_superuser:
					# Special rule for The Amplifier
					if data['newsletters'].pk == 1:
						users = User.objects.filter(is_active=True, email_newsletter_optin=True).exclude(email='')
					elif data['newsletters'].pk == 5:
						users = User.objects.filter(is_active=True, email_careers_newsletter_AU_optin=True).exclude(email='')
					else:
						users = User.objects.none()
			else:
				users = data['recipients']

			usersfiltered = []
			if statussel != '0' and request.POST['type'] != '4':
				for one_user in users:
					if one_user.membertype().pk == int(statussel):
						if request.POST['step'] == '1':
							usersfiltered.append(one_user)
						else:
							if str(one_user.pk) in request.POST.keys():
								recipient = EmailRecipient()
								recipient.message = message
								recipient.user = one_user
								recipient.to_name = one_user.get_full_name()
								recipient.to_address = one_user.email
								recipient.save()
			else:
				for one_user in users:
					if request.POST['step'] == '1':
						usersfiltered.append(one_user)
					else:
						if str(one_user.pk) in request.POST.keys():
							recipient = EmailRecipient()
							recipient.message = message
							recipient.user = one_user
							recipient.to_name = one_user.get_full_name()
							recipient.to_address = one_user.email
							recipient.save()
			
			subscribers = []
			if request.POST['type'] == '4' and request.user.is_superuser:
				for one_subscriber in NewsletterSubscriber.objects.filter(newsletter=data['newsletters'], active=True):
					if request.POST['step'] == '1':
						subscribers.append(one_subscriber)
					else:
						if ('sub' + str(one_subscriber.pk)) in request.POST.keys():
							recipient = EmailRecipient()
							recipient.message = message
							recipient.user = None
							recipient.to_name = one_subscriber.first_name + " " + one_subscriber.last_name
							recipient.to_address = one_subscriber.email
							recipient.save()
			
			if request.POST['step'] == '2':
				for f in request.FILES.getlist('upload_files'):
					ef = EmailFile(emailfile=f)
					ef.save()
					message.upload_files.add(ef)
				# Now mark it as OK to send. The email and all recipients are now in MySQL.
				# A background script on the server will process the queue.
				message.status = 0
				message.save()
			
			if request.POST['step'] == '1':
				return render_to_response('email_users_confirm.html', {'usersfiltered': usersfiltered, 'subscribers': subscribers, 'type': request.POST['type'], 'scheduling': request.POST['scheduling'], 'status': request.POST['status'], 'emailid': request.session['emailid']}, context_instance=RequestContext(request))
			else:
				return HttpResponseRedirect('/messages/email/done/')
	else:
		if request.user.is_superuser:
			typesel = '2'
		else:
			typesel = '1'
		schedsel = '0'
		statussel = '1'
		emailform = WriteEmailForm(None, user=request.user)
	return render_to_response('email_write.html', {'memberstatustypes': memberstatustypes, 'emailform': emailform, 'chapter': request.user.chapter, 'typesel': typesel, 'schedsel': schedsel, 'statussel': statussel}, context_instance=RequestContext(request))
Exemple #11
0
def rsvpemail(request, conf_id):
    # Superuser check
    if not request.user.is_superuser:
        raise Http404

    conf = get_object_or_404(Conference, pk=conf_id)
    chapter = request.user.chapter

    # Determine if form has been POSTed back
    if request.method == 'POST':
        # Validate email form data
        emailform = EmailAttendeesForm(request.POST,
                                       conference=conf,
                                       user=request.user)
        if emailform.is_valid():
            data = emailform.cleaned_data

            # Set up message
            message = EmailMessage()
            message.subject = data['subject']
            message.body = data['body']
            message.from_address = request.user.email
            message.reply_address = request.user.email
            message.sender = request.user
            message.html = True

            if int(data['from_type']) == 0:
                message.from_name = "Robogals"
            elif int(data['from_type']) == 1:
                message.from_name = request.user.chapter.name
            else:
                message.from_name = request.user.get_full_name()

            message.scheduled = False

            # Don't send it yet until the recipient list is done
            message.status = -1
            # Save to database so we get a value for the primary key,
            # which we need for entering the recipient entries
            message.save()

            # Start processing recipient list
            # Insert choices for attending, not attending etc here
            if request.POST['invitee_type'] == '1':  # All
                # Using `ConferenceAttendee`
                users = ConferenceAttendee.objects.filter(conference=conf.id)

                # Using `User`
                # id_list = ConferenceAttendee.objects.filter(conference=conf.id).values_list('user_id')
                # users = User.objects.filter(id__in = id_list, is_active=True, email_reminder_optin=True).order_by('last_name')
            elif request.POST['invitee_type'] == '2':  # Selected
                users = data['memberselect']

            for one_user in users:
                recipient = EmailRecipient()
                recipient.message = message
                recipient.to_address = one_user.email

                # Using `ConferenceAttendee`
                recipient.user = one_user.user
                recipient.to_name = one_user.full_name()

                # Using `User`
                # recipient.user = one_user
                # recipient.to_name = one_user.get_full_name()

                recipient.save()

            # Send message
            message.status = 0
            message.save()

            messages.success(request,
                             message=unicode(_("Email sent successfully")))
            return HttpResponseRedirect('/conferences/' + str(conf.pk) + '/')
    else:
        emailform = EmailAttendeesForm(None,
                                       conference=conf,
                                       user=request.user)

    # Display email form
    return render_to_response('conf_rsvp_email.html', {
        'conf': conf,
        'emailform': emailform
    },
                              context_instance=RequestContext(request))
Exemple #12
0
def importcsv(filerows, welcomeemail, defaults, chapter, updateuser,
              ignore_email):
    columns = None
    users_imported = 0
    username_pos = 0
    users_updated = 0
    existing_users = 0
    existing_emails = 0
    count = -1
    username_field_exists_flag = False
    user_already_exists = False
    msg = ""
    if 'date_joined' not in defaults:
        defaults['date_joined'] = timezone.now()
    elif defaults['date_joined'] == None:
        defaults['date_joined'] = timezone.now()
    for row in filerows:
        if any(row):
            # Create new user
            newuser = User()
            count += 1
            user_already_exists_flag = False
            # Get column names from first row, also get the positions of the fields so that we can extract their values
            # using their positions later.
            if (columns == None):
                columns = row
                if 'first_name' not in columns:
                    raise RgImportCsvException(
                        _('You must specify a first_name field'))
                else:
                    first_name_pos = columns.index('first_name')

                if 'last_name' not in columns:
                    raise RgImportCsvException(
                        _('You must specify a last_name field'))
                else:
                    last_name_pos = columns.index('last_name')

                if 'email' not in columns:
                    raise RgImportCsvException(
                        _('You must specify an email field'))
                else:
                    email_pos = columns.index('email')

                if 'username' in columns:
                    username_pos = columns.index('username')
                    username_field_exists_flag = True

                if 'mobile' in columns:
                    mobile_pos = columns.index('mobile')

                continue

            # Process row
            i = 0

            # extracting the values of the username, email, first_name and last_name fields for each row.
            if username_field_exists_flag:
                uname = row[username_pos]
            else:
                uname = ''
            email = row[email_pos]
            first_name = row[first_name_pos]
            last_name = row[last_name_pos]

            # now remove all the whitespaces from the extracted values.
            uname_data = uname.strip()
            email_data = email.strip()
            first_name_data = first_name.strip()
            last_name_data = last_name.strip()

            # check if any of the values is None or empty for a row. If yes, form an error message and ignore that row.
            if first_name_data == None or first_name_data == '':
                msg += ("<br>First name not provided for row %d - row ignored."
                        ) % count
                continue
            if last_name_data == None or last_name_data == '':
                msg += ("<br>Last name not provided for row %d - row ignored."
                        ) % count
                continue
            if email_data == None or email_data == '':
                msg += (
                    "<br>Email not provided for row %d - row ignored.") % count
                continue

            # check if the username exists, if yes, check if the 'updateuser' checkbox is ticked. If it is ticked,
            # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore.
            # Also, they must be from the same chapter
            if not check_username(uname_data):
                user_already_exists_flag = True
                if updateuser:
                    newuser = User.objects.get(username=uname_data)
                    if newuser.chapter == chapter:
                        existing_users += 1
                    else:
                        msg += (
                            "<br>Row %d has a username clash (%s) with another chapter - row ignored"
                        ) % (count, uname_data)
                        continue
                else:
                    msg += (
                        "<br>Row %d has a username clash (%s) - row ignored"
                    ) % (count, uname_data)
                    continue

            # check if the email exists for any user, if yes, check if the 'ignore_email' checkbox is ticked. If it is not ticked,
            # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore.
            # Also, they must be from the same chapter
            elif not check_email_and_chapter(email_data, chapter):
                existing_emails += 1
                if ignore_email:
                    msg += (
                        "<br>Row %d's email address (%s) matches an existing user - row ignored"
                    ) % (count, email_data)
                    continue

            for cell in row:
                colname = columns[i]
                if colname == 'first_name':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'last_name':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'email':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'username':
                    data = cell.strip()
                    if data != "":
                        new_username = data
                    else:
                        new_username = generate_unique_username(row, columns)
                    newuser.username = new_username
                elif colname == 'password':
                    data = cell.strip()
                    if data != "":
                        plaintext_password = data
                    else:
                        plaintext_password = User.objects.make_random_password(
                            6)
                    newuser.set_password(plaintext_password)
                elif colname == 'alt_email':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'mobile':
                    num = cell.strip().replace(' ', '').replace('+', '')
                    if num != '':
                        regexes = MobileRegex.objects.filter(
                            collection=chapter.mobile_regexes)
                        try:
                            number_valid = False
                            for regex in regexes:
                                matches = re.compile(regex.regex).findall(num)
                                if matches == []:
                                    matches = re.compile(
                                        regex.regex).findall("0" + num)
                                    if matches == []:
                                        continue
                                    else:
                                        num = "0" + num
                                num = regex.prepend_digits + num[regex.
                                                                 strip_digits:]
                                number_valid = True
                        except ValueError:
                            number_valid = False
                        if number_valid:
                            newuser.mobile = num
                elif colname == 'date_joined':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'dob':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'gender':
                    numval(colname, cell, newuser, defaults, [0, 1, 2])
                elif colname == 'course':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'uni_start':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'uni_end':
                    dateval(colname, cell, newuser, defaults)
                elif colname == 'university_id':
                    unis = University.objects.all()
                    uni_ids = [-1]
                    for uni in unis:
                        uni_ids.append(uni.pk)
                    numval(colname, cell, newuser, defaults, uni_ids)
                    if getattr(newuser, 'university_id', 0) == -1:
                        newuser.university_id = chapter.university_id
                elif colname == 'course_type':
                    numval(colname, cell, newuser, defaults, [1, 2])
                elif colname == 'student_type':
                    numval(colname, cell, newuser, defaults, [1, 2])
                elif colname == 'student_number':
                    stringval(colname, cell, newuser, defaults)
                elif colname == 'privacy':
                    numval(colname, cell, newuser, defaults, [0, 5, 10, 20])
                elif colname == 'dob_public':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_public':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_chapter_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'mobile_marketing_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_reminder_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'mobile_reminder_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_newsletter_optin':
                    boolval(colname, cell, newuser, defaults)
                elif colname == 'email_careers_newsletter_AU_optin':
                    boolval(colname, cell, newuser, defaults)
                else:
                    pass  # Unknown column, ignore
                # Increment column and do the loop again
                i += 1

            # If we still don't have a username and/or password
            # by this stage, let's generate one
            if getattr(newuser, 'username', '') == '':
                new_username = generate_unique_username(row, columns)
                newuser.username = new_username
            if getattr(newuser, 'password', '') == '':
                plaintext_password = User.objects.make_random_password(6)
                newuser.set_password(plaintext_password)

            # And finally...
            newuser.chapter = chapter
            newuser.save()

            # If updating an existing user, we don't need to do the rest
            if user_already_exists_flag:
                continue

            # Should be the default at the model-level,
            # but just to be sure...
            newuser.is_active = True
            newuser.is_staff = False
            newuser.is_superuser = False

            # Apply any unapplied defaults
            for key, value in defaults.iteritems():
                if key not in columns:
                    setattr(newuser, key, value)

            newuser.save()

            # Must be called after newuser.save() because the primary key
            # is required for these
            mt = MemberStatus(user_id=newuser.pk,
                              statusType_id=1,
                              status_date_start=newuser.date_joined)
            mt.save()

            # Send welcome email
            if welcomeemail:
                message = EmailMessage()
                try:
                    message.subject = welcomeemail['subject'].format(
                        chapter=chapter,
                        user=newuser,
                        plaintext_password=plaintext_password)
                except Exception:
                    newuser.delete()
                    raise RgImportCsvException(
                        _('Welcome email subject format is invalid'))
                try:
                    message.body = welcomeemail['body'].format(
                        chapter=chapter,
                        user=newuser,
                        plaintext_password=plaintext_password)
                except Exception:
                    newuser.delete()
                    raise RgImportCsvException(
                        _('Welcome email format is invalid'))
                message.from_address = '*****@*****.**'
                message.reply_address = '*****@*****.**'
                message.from_name = chapter.name
                message.sender = User.objects.get(username='******')
                message.html = welcomeemail['html']
                message.status = -1
                message.save()
                recipient = EmailRecipient()
                recipient.message = message
                recipient.user = newuser
                recipient.to_name = newuser.get_full_name()
                recipient.to_address = newuser.email
                recipient.save()
                message.status = 0
                message.save()

            users_imported += 1

    return users_imported, existing_users, existing_emails, msg
Exemple #13
0
def emailvisitattendees(request, visit_id):
    if not request.user.is_staff:
        raise Http404
    chapter = request.user.chapter
    v = get_object_or_404(SchoolVisit, pk=visit_id)
    if (v.chapter != chapter) and not request.user.is_superuser:
        raise Http404
    if request.method == 'POST':
        emailform = EmailAttendeesForm(request.POST,
                                       user=request.user,
                                       visit=v)
        if emailform.is_valid():
            data = emailform.cleaned_data

            message = EmailMessage()
            message.subject = data['subject']
            message.body = data['body']
            message.from_address = request.user.email
            message.reply_address = request.user.email
            message.sender = request.user
            message.html = True
            message.from_name = chapter.name
            message.scheduled = False

            # Don't send it yet until the recipient list is done
            message.status = -1
            # Save to database so we get a value for the primary key,
            # which we need for entering the recipient entries
            message.save()

            # Start processing recipient list
            # Send to all invitees
            if request.POST['invitee_type'] == '1':
                id_list = EventAttendee.objects.filter(
                    event=v.id).values_list('user_id')
                users = User.objects.filter(id__in=id_list,
                                            is_active=True,
                                            email_reminder_optin=True)
            # Send to invitees who have RSVP'd as attending
            elif request.POST['invitee_type'] == '2':
                id_list = EventAttendee.objects.filter(
                    event=v.id, rsvp_status=2).values_list('user_id')
                users = User.objects.filter(id__in=id_list,
                                            is_active=True,
                                            email_reminder_optin=True)
            # Send to invitees who have RSVP'd as not attending
            elif request.POST['invitee_type'] == '3':
                id_list = EventAttendee.objects.filter(
                    event=v.id, rsvp_status=4).values_list('user_id')
                users = User.objects.filter(id__in=id_list,
                                            is_active=True,
                                            email_reminder_optin=True)
            # Send to invitees who have yet to RSVP
            elif request.POST['invitee_type'] == '4':
                id_list = EventAttendee.objects.filter(
                    event=v.id, rsvp_status=1).values_list('user_id')
                users = User.objects.filter(id__in=id_list,
                                            is_active=True,
                                            email_reminder_optin=True)
            # Send to specifically selected users
            elif request.POST['invitee_type'] == '5':
                users = data['memberselect']

            for one_user in users:
                recipient = EmailRecipient()
                recipient.message = message
                recipient.user = one_user
                recipient.to_name = one_user.get_full_name()
                recipient.to_address = one_user.email
                recipient.save()

            message.status = 0
            message.save()

            messages.success(request,
                             message=unicode(_("Email sent succesfully")))
            return HttpResponseRedirect('/teaching/' + str(v.pk) + '/')
    else:
        emailform = EmailAttendeesForm(None, user=request.user, visit=v)
    return render_to_response('visit_email.html', {
        'emailform': emailform,
        'visit_id': visit_id
    },
                              context_instance=RequestContext(request))
Exemple #14
0
def invitetovisit(request, visit_id):
    if not request.user.is_staff:
        raise Http404
    chapter = request.user.chapter
    v = get_object_or_404(SchoolVisit, pk=visit_id)
    error = ''
    if (v.chapter != chapter) and not request.user.is_superuser:
        raise Http404
    if request.method == 'POST':
        inviteform = InviteForm(request.POST, user=request.user, visit=v)
        if inviteform.is_valid():
            data = inviteform.cleaned_data
            try:
                if data['action'] == '1':
                    message = EmailMessage()
                    message.subject = data['subject']
                    message.body = data['body']
                    message.from_address = request.user.email
                    message.reply_address = request.user.email
                    message.sender = request.user
                    # message.html = v.chapter.invite_email_html
                    message.html = 1
                    message.from_name = chapter.name

                    # Don't send it yet until the recipient list is done
                    message.status = -1
                    # Save to database so we get a value for the primary key,
                    # which we need for entering the recipient entries
                    message.save()

                # Send to all users who haven't opted out of workshop reminders
                if request.POST['type'] == '1':
                    users = User.objects.filter(chapter=chapter,
                                                is_active=True,
                                                email_reminder_optin=True)
                # Send to chapter committee
                elif request.POST['type'] == '2':
                    users = User.objects.filter(chapter=chapter,
                                                is_active=True,
                                                is_staff=True)
                # Send to all trained users who haven't opted out of workshop reminders
                elif request.POST['type'] == '4':
                    users = User.objects.filter(chapter=chapter,
                                                is_active=True,
                                                email_reminder_optin=True,
                                                trained=True)
                # Send to a user list
                elif request.POST['type'] == '5':
                    ul = data['list']
                    users = ul.users.all()
                # Send to specifically selected users
                else:
                    users = data['memberselect']

                for one_user in users:
                    if data['action'] == '1':
                        recipient = EmailRecipient()
                        recipient.message = message
                        recipient.user = one_user
                        recipient.to_name = one_user.get_full_name()
                        recipient.to_address = one_user.email
                        recipient.save()
                    EventAttendee.objects.filter(user=one_user,
                                                 event=v).delete()
                    ea = EventAttendee()
                    ea.event = v
                    ea.user = one_user
                    if data['action'] == '1':
                        ea.rsvp_status = 1
                    if data['action'] == '2':
                        ea.rsvp_status = 2
                    ea.actual_status = 0
                    ea.save()

                if data['action'] == '1':
                    # Now mark it as OK to send. The email and all recipients are now in MySQL.
                    # A background script on the server will process the queue.
                    message.status = 0
                    message.save()

                if data['action'] == '1':
                    messages.success(
                        request,
                        message=unicode(
                            _("Invitations have been sent to the selected volunteers"
                              )))
                if data['action'] == '2':
                    messages.success(
                        request,
                        message=unicode(
                            _("Selected volunteers have been added as attending"
                              )))
                return HttpResponseRedirect('/teaching/' + str(v.pk) + '/')
            except Exception as e:
                error = e.args[0]
    else:
        inviteform = InviteForm(None, user=request.user, visit=v)
    return render_to_response('visit_invite.html', {
        'inviteform': inviteform,
        'visit_id': visit_id,
        'error': error
    },
                              context_instance=RequestContext(request))