Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send scheduled email with Crontab in Django

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.

like image 694
RlM Avatar asked Oct 28 '25 04:10

RlM


1 Answers

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.mail import send_mail
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        # ... do the job here
        send_mail(
            # ...
        )
        print('Successfully sent')

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.

like image 147
Dos Avatar answered Oct 29 '25 17:10

Dos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!