[Answer]-Send_mail() doesn't work on page reload

1👍

The issue is with the placement of the send_mail() call which is inside the class definition. Django will often lazy-load objects, meaning that the code will only be imported when it is first used. In your case, when you first execute the view, Django imports the module containing your view, and, while parsing the IndexView class, sends out an email. However, on subsequent page views, the code has already been loaded, the class definition is not reparsed and so the send_mail() call is never made.

You have to move the send_mail() call inside a view function within your IndexView class.

class IndexView(generic.ListView):
    ....
    def get(self, request):
        # Send email on every get request.
        send_mail('Test Dj', 'Here is the message.', 'from@example.com', ['to@example'], fail_silently=False)
        return super(IndexView, self).get(request)

Leave a comment