Home > Software engineering >  How to send scheduled email with Crontab in Django
How to send scheduled email with Crontab in Django

Time:04-21

I like to send scheduled emails in Django with Crontab. I made a very simple app to test how can I send an email in every minutes (just for testing purposes). I think I am doing something wrong, because I can't get the mails.

users/cron.py

from django.core.mail import send_mail

def my_scheduled_job():
    
    send_mail(
        'subject',
        'Here is the message.',
        '[email protected]',
        ['[email protected]'],
        fail_silently=False,
    )
    print('Successfully sent')

settings.py

CRONJOBS = [
    ('*/1 * * * *', 'users.cron.my_scheduled_job')
]

I added the job like this:

python3 manage.py crontab add

then

python3 manage.py runserver

My mailing server configured fine, every other emails are sent, but I can't get these emails, nothing happens. I don't like to use Celery or Django Q.

CodePudding user response:

Take a look at django-mailer:

https://github.com/pinax/django-mailer

It can replace the standard email backend and stores message queue in the db (so no Celery needed).

You just schedule it's management command through regular cron and that's basically it.

CodePudding user response:

You can use built-in Django commands to avoid third party integrations or external libraries. For example you can add the following in a my_app/management/commands/my_scheduled_job.py file:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        # ... do the job here

and then you can just configure your crontab command as usual, for example every day at 8PM:

0 20 * * * python manage.py my_scheduled_job

Here additional info about custom Django commands.

  • Related