djangocelerydjango-cron

Gmail Schedule Send Email in Django


I want to mimic the functionality that Gmail has, where you can choose to send an email at a certain time (maybe 3:34 am tomorrow) in Django.

I looked at something like django-crontab (https://pypi.org/project/django-crontab/).

I came up with an idea to use django-crontab to achieve this:

  1. Make a crontab that runs every minute
  2. Every minute, check if there are any emails that need to be sent
  3. Send out those emails

This feels a bit hacky and over-engineered. Is there a better way? Thanks!


Solution

  • You can check out celery and how to integrate it with django. Once done, task scheduling is easy,first add your gmail configuration in settings.py as follows:

    EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'your_email'
    EMAIL_HOST_PASSWORD = 'your password'
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
    EMAIL_PORT = 465
    

    Then in your tasks.py you can add the function for scheduling emails as follows:

    from django.template.loader import render_to_string
    from django.core.mail import EmailMessage
    
    
    @periodic_task(
    run_every=(crontab(hour=3, minute=34)), #runs exactly at 3:34am every day
    name="Dispatch_scheduled_mail",
    reject_on_worker_lost=True,
    ignore_result=True)
    def schedule_mail():
        message = render_to_string('app/schedule_mail.html')
        mail_subject = 'Scheduled Email'
        to_email = getmail
        email = EmailMessage(mail_subject, message, to=[to_email])
        email.send()
    

    Then finally your email template 'schedule_mail.html'

    {% autoescape off %}
    Hello ,
    
    This is a test email
    if you are seeing this, your email got delivered!
    
    Regards,
    Coding Team.
    {% endautoescape %}
    

    And the command to run celery service as beat:

    celery -A yourapp beat --loglevel=info
    

    replace 'yourapp' with name of your app. Cheers!!