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.

utils.py 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from django.conf import settings
  2. from django.core.exceptions import ValidationError
  3. from django.core.files import File
  4. from django.utils.encoding import force_text
  5. from post_office import cache
  6. from .compat import string_types
  7. from .models import Email, PRIORITY, STATUS, EmailTemplate, Attachment
  8. from .settings import get_default_priority
  9. from .validators import validate_email_with_name
  10. def send_mail(subject, message, from_email, recipient_list, html_message='',
  11. scheduled_time=None, headers=None, priority=PRIORITY.medium):
  12. """
  13. Add a new message to the mail queue. This is a replacement for Django's
  14. ``send_mail`` core email method.
  15. """
  16. subject = force_text(subject)
  17. status = None if priority == PRIORITY.now else STATUS.queued
  18. emails = []
  19. for address in recipient_list:
  20. emails.append(
  21. Email.objects.create(
  22. from_email=from_email, to=address, subject=subject,
  23. message=message, html_message=html_message, status=status,
  24. headers=headers, priority=priority, scheduled_time=scheduled_time
  25. )
  26. )
  27. if priority == PRIORITY.now:
  28. for email in emails:
  29. email.dispatch()
  30. return emails
  31. def get_email_template(name, language=''):
  32. """
  33. Function that returns an email template instance, from cache or DB.
  34. """
  35. use_cache = getattr(settings, 'POST_OFFICE_CACHE', True)
  36. if use_cache:
  37. use_cache = getattr(settings, 'POST_OFFICE_TEMPLATE_CACHE', True)
  38. if not use_cache:
  39. return EmailTemplate.objects.get(name=name, language=language)
  40. else:
  41. composite_name = '%s:%s' % (name, language)
  42. email_template = cache.get(composite_name)
  43. if email_template is not None:
  44. return email_template
  45. else:
  46. email_template = EmailTemplate.objects.get(name=name,
  47. language=language)
  48. cache.set(composite_name, email_template)
  49. return email_template
  50. def split_emails(emails, split_count=1):
  51. # Group emails into X sublists
  52. # taken from http://www.garyrobinson.net/2008/04/splitting-a-pyt.html
  53. # Strange bug, only return 100 email if we do not evaluate the list
  54. if list(emails):
  55. return [emails[i::split_count] for i in range(split_count)]
  56. def create_attachments(attachment_files):
  57. """
  58. Create Attachment instances from files
  59. attachment_files is a dict of:
  60. * Key - the filename to be used for the attachment.
  61. * Value - file-like object, or a filename to open OR a dict of {'file': file-like-object, 'mimetype': string}
  62. Returns a list of Attachment objects
  63. """
  64. attachments = []
  65. for filename, filedata in attachment_files.items():
  66. if isinstance(filedata, dict):
  67. content = filedata.get('file', None)
  68. mimetype = filedata.get('mimetype', None)
  69. else:
  70. content = filedata
  71. mimetype = None
  72. opened_file = None
  73. if isinstance(content, string_types):
  74. # `content` is a filename - try to open the file
  75. opened_file = open(content, 'rb')
  76. content = File(opened_file)
  77. attachment = Attachment()
  78. if mimetype:
  79. attachment.mimetype = mimetype
  80. attachment.file.save(filename, content=content, save=True)
  81. attachments.append(attachment)
  82. if opened_file is not None:
  83. opened_file.close()
  84. return attachments
  85. def parse_priority(priority):
  86. if priority is None:
  87. priority = get_default_priority()
  88. # If priority is given as a string, returns the enum representation
  89. if isinstance(priority, string_types):
  90. priority = getattr(PRIORITY, priority, None)
  91. if priority is None:
  92. raise ValueError('Invalid priority, must be one of: %s' %
  93. ', '.join(PRIORITY._fields))
  94. return priority
  95. def parse_emails(emails):
  96. """
  97. A function that returns a list of valid email addresses.
  98. This function will also convert a single email address into
  99. a list of email addresses.
  100. None value is also converted into an empty list.
  101. """
  102. if isinstance(emails, string_types):
  103. emails = [emails]
  104. elif emails is None:
  105. emails = []
  106. for email in emails:
  107. try:
  108. validate_email_with_name(email)
  109. except ValidationError:
  110. raise ValidationError('%s is not a valid email address' % email)
  111. return emails