0

I created a Contact form on my website built in Django but emails sent from the form do not seem to actually send. Here is my form code in forms.py:


class ContactForm(forms.Form):
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)

Here is the code in my views.py:

def contact(request, success=""):
    submitted = False
    template_name = "main/contact.html"
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['MYEMAILHERE'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect("success/")
    if success != "":
        submitted = True

    context = {"form": form,
               "submitted": submitted}
    return render(request, template_name, context)

And finally here is the forms html code:

{% load crispy_forms_tags %}
<h1>Contact Us</h1>
<form method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="form-actions">
      <button type="submit" class="btn btn-primary mb-2">Send</button>
    </div>
</form>

If any other code is needed to help debug please let me know and I will include it. Thank you.

  • 1
    can you post your email settings in the django settings.py ? – Linh Nguyen Nov 28 '19 at 02:46
  • Oh that might be the source of the problem. The only thing I have is I specified EMAIL_BACKEND to be EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I hardcoded my email into the views.py Are there other things I need to include in settings.py to make this work? – DesperateCoder Nov 28 '19 at 03:05
  • yes you need to use it like [this](https://stackoverflow.com/a/6367458/11225821) answer right here but it won't work for gmail since they changed it, so you need to use some third party service like sendgrid or mailgun – Linh Nguyen Nov 28 '19 at 03:09

1 Answers1

0

put this mail configuration in your settings.py

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER ='your mail id'
EMAIL_HOST_PASSWORD = 'your password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

import this in your views.py

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

add this in views.py

send_mail(subject, message, from_email/settings.EMAIL_HOST_USER, ['your mail/to mail'],fail_silently=False)

NOTE: make sure that less secure app ON if it is gmail account less secure app