Search code examples
pythondjangodjango-formsgmail-imap

How can I get my website "Contact Me" Form to arrive at my Gmail?


I am trying to build a contact me form for my portfolio but I am running into issues.

Traceback
File "..\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    SMTPSenderRefused at /
(530, b'5.5.1 Authentication Required. Learn more at\n5.5.1  https://support.google.com/mail/?p=WantAuthError c17sm3159820ild.31 -gsmtp', 'The_email_I_use_on_form@gmail.com')

views.py

def index_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid():
            # Send email goes here
            sender_name = form.cleaned_data['name']
            sender_email = form.cleaned_data['email']
            message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
            send_mail('New Enquiry', message, sender_email,
                      ['to_me@gmail.com'])
            return HttpResponse("Thanks for contacting, We will be in touch soon!")
    else:
        form = ContactForm()
    return render(request, 'index.html', {'form': form })

Settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PWD')

Forms.py

from django import forms 

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

I went into my settings on Gmail to see if there could be something in the security settings blocking me from receiving the form submissions, I tried changing the security setting that allows access for less secure apps. Should I choose a different email provider or is there a work-around for this?


Solution

  • Do you have 2-factor-authentication enabled for your Gmail account? If so you may need to use an "app password", rather than your regular email password.

    https://support.google.com/accounts/answer/185833