def send_email(user_id, start_date, end_date): user = User.objects.get(pk=user_id) print 'Found user', user # First find the user's verified, primary email address. primary_email = EmailAddress.objects.get_primary(user) print 'Primary email', primary_email if not primary_email or not primary_email.verified: # No email found; skip. return # Now see if there are any updates. template_context = digests.daily_context(user, start_date, end_date) if not template_context['any_with_activity']: # No activity found; skip. return # Build email. print 'Building email' html_content = render_to_string('dashboard/digest_html.html', template_context) text_content = render_to_string('dashboard/digest_plaintext.txt', template_context) # Send email. print 'Sending email' subject = '[Volunteer HQ] Updates for {0}'.format(start_date.date()) from_email = '*****@*****.**' to_email = primary_email.email msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, 'text/html') msg.send()
def digest(request, form_class=DigestRangeForm, template_name='dashboard/digest.html', *args, **kwargs): now = datetime.datetime.now() start_date = None end_date = None mimetype = None if 'submit' in request.GET: form = form_class(request.GET) if form.is_valid(): start_date = datetime.datetime.strptime(form.cleaned_data['start_date'], TIME_FORMAT) end_date = datetime.datetime.strptime(form.cleaned_data['end_date'], TIME_FORMAT) # Enforce max 7 days. if end_date - start_date > datetime.timedelta(days=7): start_date = end_date - datetime.timedelta(days=7) else: form = form_class(initial=dict( start_date=now - datetime.timedelta(days=1), end_date=now, )) template_context = dict( form=form, ) if start_date and end_date: user = request.user template_context = digests.daily_context(user, start_date, end_date) if request.GET.get('submit') == 'html': template_name = 'dashboard/digest_html.html' return render_to_response(template_name, template_context, RequestContext(request)) if request.GET.get('submit') == 'plaintext': template_name = 'dashboard/digest_plaintext.txt' return render_to_response(template_name, template_context, RequestContext(request), mimetype='text/plain') if request.GET.get('submit') == 'email': send_email.delay(user.id, start_date, end_date) return HttpResponse('Email will be sent if any activity detected.', mimetype='text/plain') else: return render_to_response(template_name, template_context, RequestContext(request))