send_expiration_reminders.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """ Send reminders for contribution that are about to expire
  2. It offers a way for contributors to opt-in keeping the data one year more (or
  3. deleting it right now).
  4. Reminders are sent when the script is called exactly `n` days before the
  5. expiration date.
  6. This `n` can be configured via `DATA_EXPIRATION_REMINDERS` setting.
  7. """
  8. from django.conf import settings
  9. from django.core.mail import send_mail
  10. from django.core.management.base import BaseCommand, CommandError
  11. from django.template.loader import get_template
  12. from ...models import Contrib
  13. class Command(BaseCommand):
  14. help = __doc__
  15. def add_arguments(self, parser):
  16. parser.add_argument(
  17. '--dry-run', default=False, action='store_true',
  18. help="Do not actually send emails, just pretend to")
  19. def handle(self, dry_run, *args, **options):
  20. if dry_run:
  21. self.stderr.write('DRY RUN MODE: we do not actually send emails.')
  22. for ndays in settings.DATA_EXPIRATION_REMINDERS:
  23. expirating_contribs = Contrib.objects.expires_in_days(ndays)
  24. for contrib in expirating_contribs:
  25. if not contrib.email:
  26. self._warn_no_email(contrib, ndays)
  27. else:
  28. if not dry_run:
  29. self.send_expiration_reminder(contrib, ndays)
  30. self._log_sent_email(contrib, ndays)
  31. def _warn_no_email(self, contrib, ndays):
  32. self.stderr.write(
  33. 'WARNING : the contribution {} is about to expire in {} days but'
  34. + 'do not define a contact email.'.format(
  35. contrib, ndays))
  36. def _log_sent_email(self, contrib, ndays):
  37. self.stderr.write(
  38. "Sent reminder email to for {} expiration in {} days".format(
  39. contrib, ndays))
  40. def send_expiration_reminder(self, contrib, ndays):
  41. subject = get_template(
  42. 'contribmap/mails/expiration_reminder.subject')
  43. body = get_template(
  44. 'contribmap/mails/expiration_reminder.txt')
  45. context = {
  46. 'contrib': contrib,
  47. 'ndays': ndays,
  48. }
  49. send_mail(
  50. subject.render(context),
  51. body.render(context),
  52. settings.DEFAULT_FROM_EMAIL,
  53. [contrib.email],
  54. )