Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions django_mailer/management/commands/cleanup_mail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import datetime
import logging
from optparse import make_option

from django.core.management.base import BaseCommand

from django_mailer.management.commands import create_handler
from django_mailer.models import Message


class Command(BaseCommand):
help = 'Place deferred messages back in the queue.'
option_list = BaseCommand.option_list + (
make_option('-d', '--days', type='int', default=90,
help="Cleanup mails older than this many days, defaults to 90."),
)

def handle(self, verbosity, days, **options):
# Delete mails and their related logs and queued created before X days
logger = logging.getLogger('django_mailer')
handler = create_handler(verbosity)
logger.addHandler(handler)

today = datetime.date.today()
cutoff_date = today - datetime.timedelta(days)
count = Message.objects.filter(date_created__lt=cutoff_date).count()
Message.objects.filter(date_created__lt=cutoff_date).delete()
logger.warning("Deleted %s mails created before %s " %
(count, cutoff_date))
14 changes: 14 additions & 0 deletions django_mailer/tests/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,17 @@ def test_retry_deferred(self):
self.assertEqual(non_deferred_messages.count(), 1)
call_command('retry_deferred', verbosity='0', max_retries=3)
self.assertEqual(non_deferred_messages.count(), 3)

def test_cleanup_mail(self):
"""
The ``cleanup_mail`` command deletes mails older than a specified
amount of days
"""
today = datetime.date.today()
self.assertEqual(models.Message.objects.count(), 0)
models.Message.objects.create()
prev = today - datetime.timedelta(31)
models.Message.objects.create(date_created=prev)
call_command('cleanup_mail', days=30)
self.assertEqual(models.Message.objects.count(), 1)

4 changes: 4 additions & 0 deletions docs/usage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,14 @@ you can run:
* ``retry_deferred`` will move any deferred mail back into the normal queue
(so it will be attempted again on the next ``send_mail``).

* ``cleanup_mail`` will delete mails created before an X number of days
(defaults to 90).

You may want to set these up via cron to run regularly::

* * * * * (cd $PROJECT; python manage.py send_mail >> $PROJECT/cron_mail.log 2>&1)
0,20,40 * * * * (cd $PROJECT; python manage.py retry_deferred >> $PROJECT/cron_mail_deferred.log 2>&1)
0 1 * * * (cd $PROJECT; python manage.py cleanup_mail --days=30 >> $PROJECT/cron_mail_cleanup.log 2>&1)

This attempts to send mail every minute with a retry on failure every 20 minutes.

Expand Down