Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

email_service.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from datetime import datetime, timedelta
  2. from django.core.mail import send_mail
  3. from django.template import Template, Context
  4. from django.http import HttpResponse
  5. from django.conf import settings
  6. from .models import ScheduledReport, ScheduledReportGroup, ReportRecipient
  7. class ScheduledReportConfig(object):
  8. def __init__(self, scheduled_report):
  9. """
  10. Expects a scheduled report object and inititializes
  11. its own scheduled_report attribute with it
  12. """
  13. self.scheduled_report = scheduled_report
  14. def get_report_config(self):
  15. """
  16. Returns the configuration related to a scheduled report, needed
  17. to populate the email
  18. """
  19. return {
  20. "template_context": self._get_related_reports_data(),
  21. "recipients": self._get_report_recipients()
  22. }
  23. def _get_related_reports_data(self):
  24. """
  25. Returns the list of reports data which needs to be sent out in a scheduled report
  26. """
  27. pass
  28. def _get_report_recipients(self):
  29. """
  30. Returns the recipient list for a scheduled report
  31. """
  32. pass
  33. def create_email_data(content=None):
  34. content = '''
  35. ''' + str(content) + ''''''
  36. return content
  37. def send_emails():
  38. current_time = datetime.utcnow()
  39. scheduled_reports = ScheduledReport.objects.filter(next_run_at__lt = current_time)
  40. for scheduled_report in scheduled_reports:
  41. report_config = ScheduledReportConfig(scheduled_report).get_report_config()
  42. """ Specify the template path you want to send out in the email. """
  43. template = Template(create_email_data('path/to/your/email_template.html'))
  44. """ //Create your email html using Django's context processor """
  45. report_template = template.render(Context(report_config['template_context']))
  46. scheduled_report.save()
  47. if not scheduled_report.subject:
  48. """ Handle exception for subject not provided """
  49. if not report_config['recipients']:
  50. """ Handle exception for recipients not provided """
  51. send_mail(
  52. scheduled_report.subject, 'Here is the message.',
  53. settings.EMAIL_HOST_USER, report_config['recipients'],
  54. fail_silently=False, html_message=report_template
  55. )