'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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | maciek.glowka |
