Issue
I've created a template in Django which has as function to wish a happy birthday to a client. I'd like to set that message in such a way it'd be send to the client every year for his birthday. I think the best way to do this is to create a cron job. However, I am not familiar with cron jobs, and I would like your help.
I've created an attribute birthday_date
that will give us the birthday date as day month
. Here's what I've done so far :
#!/bin/bash
MANAGE="../venv/bin/python ../manage.py"
Could anyone be able to tell me how could I do this?
Thanks in advance!
Solution
A simple solution would be to create a custom management command which will send the happy birthday emails of the day and run it every day via a cronjob.
This an example custom command, yours will probably be different, depending on how you store your user data:
# app/management/commands/send_daily_birthday_greetings.py
"""
Custom management command that sends an email to all users
born on the current day and month.
"""
from django.core.management import BaseCommand
from django.core.mail import send_mail
from django.utils import timezone
from someplace import User
class Command(BaseCommand):
def handle(self, **options):
today = timezone.now().date()
for user in User.objects.filter(birth_date__day=today.day, birth_date__month=today.month):
subject = 'Happy birthday %s!' % user.first_name
body = 'Hi %s,\n...' + user.first_name
send_mail(subject, body, '[email protected]', [user.email])
Then edit your crontab configuration with crontab -e
this way:
# m h dom mon dow command
0 10 * * * /path/to/your/python/executable/python /path/to/your/manage.py send_daily_birthday_greetings
This will send the emails at 10h00 every day, you may change the time as you wish.
Answered By - aumo