Not able to get email when user submits the form

I have created contact form with react and connected it with mysql database hosted using RDS. i used django for building the database. before some days i was able to get email when i am submitting the form and the data was also been stored in the database but now when i am submitting the form i am not getting an email notification of submission but i can see the data in my database. i also tried to send test email from the console and it worked. when i changed the API from urls.py and then i submitted the form, i got the mail but when i did the submission again i did not get any mail.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config('DB_NAME', default='myportfolio'),
        'USER': config('DB_USER', default='root'),
        'PASSWORD': config('DB_PASSWORD', default=''),
        'HOST': config('DB_HOST', default=''),
        'PORT': config('DB_PORT', default='3306'),
    }
}

# Email backend configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') 

@csrf_exempt
def form_submission_view(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            name = data.get('name')
            email = data.get('email')
            subject = data.get('subject')
            message = data.get('message')

            if not name:
                return JsonResponse({'error': 'Name is required'}, status=400)
            if not email:
                return JsonResponse({'error': 'Email is required'}, status=400)
            if not subject:
                return JsonResponse({'error': 'Subject is required'}, status=400)
            if not message:
                return JsonResponse({'error': 'Message is required'}, status=400)

           
            Form.objects.create(name=name, email=email, subject=subject, message=message)

         
            send_mail(
                'New Form Submission',
                f'You have a new form submission:\n\nName: {name}\nEmail: {email}\nSubject: {subject}\nMessage: {message}',
                settings.EMAIL_HOST_USER,
                [settings.EMAIL_HOST_USER],
                fail_silently=False,
            )

            
            return JsonResponse({'message': 'Form submitted successfully!'})
        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'error': 'Invalid data'}, status=400)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=405)

Welcome @Aamir10-02 !

So you’re saying that when you start the server, the first time you try to submit the form to send an email, everything works. The second time you try it, it fails.

If you restart the server does it work the first time again?

The send_mail method does return a value. It might be worth capturing that value and printing it.

Also, are you seeing any of the error messages either in your console, logs, or in the browser? What status code are you getting as a response?

Not the first time, before few days i am getting the mail but now i am not, but when i changed this line ->path(‘formApi/’, views.formApi, name=‘form-api’), from the below code i got the email (before it was form then i changed it to formApi).

from django.urls import path
from django.contrib import admin
from form import views
from form.views import form_submission_view

urlpatterns = [

path('formApi/', views.formApi, name='form-api'),  
path('formApi/<int:id>/', views.formApi, name='form-details'),
path('admin/', admin.site.urls),
path('form/', form_submission_view, name='form_submission'),

I respect that English is not your first language, but unfortunately, I cannot understand what you’re trying to tell me here.

If you have made a change to your urls.py, please show both versions - the verson that worked, and the version that doesn’t work. (And clearly identify each one.)

Thank you for your response. I assumed the context of my previous messages was clear, which is why I kept it concise, but I’ll be sure to provide more details moving forward.

To clarify, I’m not getting any error messages in the console. The form data is being stored in the database successfully, and the status code from the POST request is 201, indicating that everything seems to be working from the backend’s perspective. However, the email is not being sent after the first successful attempt, and this behavior persists even after restarting the server. My settings.py, views.py, and urls.py configurations have already been shared.

Could there be something else I should investigate in the email-sending logic?

My current urls.py code :
from django.urls import path
from django.contrib import admin
from form import views
from form.views import form_submission_view

urlpatterns = [

path('formApi/', views.formApi, name='form-api'),  # Changed the path to 'formApi'
path('formApi/<int:id>/', views.formApi, name='form-details'),
path('admin/', admin.site.urls),
path('form/', form_submission_view, name='form_submission'),  # This handles form submission

]

My previous urls.py code : from django.urls import path
from django.contrib import admin
from form import views
from form.views import form_submission_view

urlpatterns = [

path('form/', views.formApi, name='form-api'),  # Changed the path to 'formApi'
path('formApi/<int:id>/', views.formApi, name='form-details'),
path('admin/', admin.site.urls),
path('form/', form_submission_view, name='form_submission'),  # This handles form submission

]

and here is the output of my console

PS D:\my-portfolio> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks…

System check identified no issues (0 silenced).
September 15, 2024 - 14:40:49
Django version 5.0.7, using settings ‘myform.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

[15/Sep/2024 14:41:57] “OPTIONS /formApi/ HTTP/1.1” 200 0
[15/Sep/2024 14:41:57] “POST /formApi/ HTTP/1.1” 201 33

I don’t see a request being issued to form/. I don’t see how your form_submission_view is even being called.

The reason the request is going to /formApi/ and not /form/ is that I’ve updated the URL in my frontend code to use /formApi/, which is handled by views.formApi.

This is my frontend connection const response = await axios.post(‘http://127.0.0.1:8000/formApi/’,

Ok, but what does this have to do with the view that you are asking about (form_submission_view)?

Invoking this url is going to call something called views.formApi, not form_submission_view.

Thank you for your response, in my urls.py the URL pattern /form/ is supposed to call the form_submission_view function form_submission_view includes the logic for getting the email. However, it seems that /formApi/ is working, but /form/ is not handling POST requests as expected.

For understanding, I have verified that /form/ should map to form_submission_view and that this view is designed to handle POST requests. I have also tested the /form/ endpoint in Postman and received a 405 Method Not Allowed response, while /formApi/ functions correctly.

I need to know if there is a misconfiguration or another issue causing /form/ to not handle requests as expected.

You posted from your logs:

I see no request to /form/ here. This doesn’t even show you trying to submit to that view. If you’ve got something trying to reference that URL, you are not showing it with the information you have posted so far.

Thank you so much for your assistance!

After your guidance, I made the following changes to resolve the issue with email notifications:

Updated urls.py, I changed the URL configuration to ensure that the form_submission_view was correctly routed. Specifically, I updated the urls.py from:

from form.views import form_submission_view

to: (highlighted the following line)

# from form.views import form_submission_view

and made sure the path for the form submission was correctly set to :

path('form/', views.form_submission_view, name='form_submission')

After making these changes, I was able to receive the email notifications as expected. Your help was invaluable in resolving this issue. Thanks again!