Issue
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
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.
Answered By - Dos Answer Checked By - Gilberto Lyons (WPSolving Admin)