Forums

How to solve Django send_mail schedule problem?

I am using Pythonanywhere (PA) and like to use the PA's task scheduler (it runs every day and checks if it is Wednesday or not) to send scheduled emails. I made a new file in my app folder called: weeklyemailmm.py. The email settings in the setting.py works with other emailing stuff on my site. What am I doing wrong?

I try to use the code below:

from django.core.mail import send_mail
import datetime
from django.conf import settings

settings.configure(settings, DEBUG=True)


today = datetime.date.today()
weekday = today.weekday()

subject = 'New weekly email'
message = 'Hi there!'

if (weekday == 2):
    try:
        send_mail(
        'Subject here',
        'Here is the message.',
        'from@gmail.com',
        ['to@gmail.com'],
        fail_silently=False,
        )

        print('It is Wednesday, email sent')
    except:
        print('It is not Wednesday')
else:
    print('Email does not sent')

On this way I always get It is not Wednesday.

If I delete the try-except part and outdent it says:

RecursionError: maximum recursion depth exceeded while calling a Python object

If I delete the settings.configure(settings, DEBUG=True) that could be possibly wrong it say:

django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

You are passing settings as argument to settings.configure, which causes the recursion problem. Take a look on the settings.configure docs and use them in a way that fits your setup: https://docs.djangoproject.com/en/4.0/topics/settings/.

Yes, you right I edited it, thank you! Unfortunately it still not sends the email. The very strange thing for me if I add the code to the views.py and run it, it works.

Remove the fail_silently, so you can see what the error is when you're sending the email. Also, make sure that the settings that you're loading in each of the environments are the same settings.