send_expiration_reminders.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. from ...tokens import ContribTokenManager
  14. class Command(BaseCommand):
  15. help = __doc__
  16. def add_arguments(self, parser):
  17. parser.add_argument(
  18. '--dry-run', default=False, action='store_true',
  19. help="Do not actually send emails, just pretend to")
  20. def handle(self, dry_run, *args, **options):
  21. if dry_run:
  22. self.stderr.write('DRY RUN MODE: we do not actually send emails.')
  23. for ndays in settings.DATA_EXPIRATION_REMINDERS:
  24. expirating_contribs = Contrib.objects.expires_in_days(ndays)
  25. for contrib in expirating_contribs:
  26. if not contrib.email:
  27. self._warn_no_email(contrib, ndays)
  28. else:
  29. if not dry_run:
  30. self.send_expiration_reminder(contrib, ndays)
  31. self._log_sent_email(contrib, ndays)
  32. def _warn_no_email(self, contrib, ndays):
  33. self.stderr.write(
  34. 'WARNING : the contribution {} is about to expire in {} days but'
  35. + 'do not define a contact email.'.format(
  36. contrib, ndays))
  37. def _log_sent_email(self, contrib, ndays):
  38. self.stderr.write(
  39. "Sent reminder email to for {} expiration in {} days".format(
  40. contrib, ndays))
  41. def send_expiration_reminder(self, contrib, ndays):
  42. subject = get_template(
  43. 'contribmap/mails/expiration_reminder.subject')
  44. body = get_template(
  45. 'contribmap/mails/expiration_reminder.txt')
  46. mgmt_token = ContribTokenManager().mk_token(contrib)
  47. context = {
  48. 'contrib': contrib,
  49. 'ndays': ndays,
  50. 'isp': settings.ISP,
  51. 'management_link': contrib.make_management_url(mgmt_token),
  52. }
  53. send_mail(
  54. subject.render(context),
  55. body.render(context),
  56. settings.DEFAULT_FROM_EMAIL,
  57. [contrib.email],
  58. )