Search code examples
djangodjango-email

Send Weekly Email Notifications to Users regarding any changes in data


What are ways to send automatic weekly email notifications to users upon any update or changes in the data in a django project ?


Solution

  • I'll describe the simplest solution I'm aware of. There are also much, much more sophisticated approaches to this problem.

    Fundamentally, you need three things:

    1. A task runner (I recommend configuring cron jobs with django-kronos)
    2. An SMTP provider (I recommend Mailgun, which is super simple to set up with Django and gives you some test credits out of the box).
    3. Email templates (write yourself & render to string w/ Django -- Mailgun has some good open source templates as well on their blog)

    Example: django-kronos provides decorators for registering functions as cron jobs (this assumes your web server is Linux-based). These jobs can be installed as part of your deploy process from the command line:

    ./manage.py installtasks
    

    For kronos to find tasks, they must be located in cron.py files inside of your apps.

    # myapp/cron.py
    
    import kronos
    
    from django.contrib.auth.models import user
    
    from myapp.services import check_for_changes, notify_user_of_change
    
    
    # Register cron job to run once a week (every Sunday) at midnight
    @kronos.register('0 0 * * 0')
    def notify_about_changes():
        """Sets up a cron job and runs this service function once a day.
    
            Installed With:
               ``./manage.py installtasks``
        """
        all_my_users = User.objects.all()
        for user in all_my_users:
            changes = check_for_changes(user)
            for change in changes:
                notify_user_of_change(user, change)
    

    Note that it's a good practice to keep your task function as "thin" as possible. In your case, you're (a) checking for changes, then (b) notifying about each change. These could each be a function that accepts a user instance as a param, or they could be model methods. In any case, the hard work should be handled elsewhere.