[Django]-Django – how to send mail 5 days before event?

4👍

If you break this down into two parts, it will be easier. The parts are

  1. Send the reminder emails
  2. Run the script every day

For the first part, I would begin by installing the outstanding django-extensions package so that it is easy to run scripts. (Check your INSTALLED_APPS, you may have it already.) Having the python-dateutil package will be helpful too.

Then I would write my script. Let’s say your app is called “myapp”. Create a directory under “myapp” called “scripts”, and create an empty __init__.py in there.

Now create your script file in “myapp/scripts/remind_players.py”. It will look something like this:

from datetime import date
from datutil.relativedelta import relativedelta
from django.mail import send_mail  # I think this is right.
from myapp.models import Tournament

def run():
    # find our tournaments that start five days from now.
    for tournament in Tournament.objects.filter(tournament_start_date=date.today() + relativedelta(days=5)):

        # find the players that are registered for the tournament
        for player in tournament.registered_player_set():
            send_mail(...)

To run your script manually, you would run

python manage.py runscript remind_players

(PROTIP: make sure that your test database only contains your own email address. It would be embarrassing to have your test system sending out emails to everyone.)

(PROTIP: you can also configure Django to put email messages in the logs, rather than actually sending them.)

For the second part, you’ll have to find a way to schedule the job to run every day. Usually, your operating system will provide a way to do that. If you’re on Unix/Linux, you’ll use “cron”. If you’re on Windows, you’ll use “Scheduled Tasks”. (There are other options for scheduling, but these are the most common.)

1👍

You can set this mail send function as cron job。You can schedule it by crontab or Celery if Your team has used it.

👤Hayden

Leave a comment