Search code examples
pythonhtmldjangosmtpcontact-form

Making a functional contact form using django


I'm created a website for a friend. I have created a contact form which he would like people to use and the messages will directly be sent to his own personal email address. I can't seem to get it working. I'm currently testing using my own outlook account and eventually would like to be using his Gmail account. please see my code below. Any input would be greatly appreciated.

I did end up getting it working using mailtrap, but as far as im aware i would need to pay to redirect to an email address of my choosing?

Settings:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587

Contact.html

{% extends 'portfolio/main.html' %} {% block content %}
{% load crispy_forms_tags %}
  <!--Section heading-->
  <h2 class="h1-responsive font-weight-bold text-center my-4">
    Contact vstheworld
  </h2>
  <!--Section description-->
  <p class="text-center w-responsive mx-auto mb-5">
    Do you have any questions? Please do not hesitate to contact us directly.
    Our team will come back to you within a matter of hours to help you.
  </p>

  <!-- Wrapper container -->
  <div class="container py-4">
    <form method="POST">
      {% csrf_token %}
          {{form|crispy}}
          <div class="d-grid">
            <br>
            <button class="btn btn-dark btn-lg" id="form-submit" type="submit">
              Submit
            </button>
          </div>
    </form>
  </div>
  {% endblock content %}

forms.py

from django import forms

class contactForm(forms.Form):
    full_name = forms.CharField(max_length = 50)
    email_address = forms.EmailField(max_length= 50)
    message = forms.CharField(widget = forms.Textarea, max_length = 2000)

views.py

from django.shortcuts import render, redirect
from .forms import contactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse


def vswPortfolio(request):
    return render(request, 'portfolio/home.html')


def vswProject(request, pk):
    return render(request, 'portfolio/project.html')


def vswContact(request):
    if request.method == 'POST':
        form = contactForm(request.POST)
        if form.is_valid():
            subject = "Website Inquiry" 
            body = {
            'full_name': form.cleaned_data['full_name'], 
            'email': form.cleaned_data['email_address'], 
            'message':form.cleaned_data['message'], 
            }
            message = "\n".join(body.values())

            try:
                send_mail(subject, message, '', ['[email protected]']) 
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect ('contact')
      
    form = contactForm()
    return render(request, "portfolio/contact.html", {'form':form})

urls

from django.urls import path
from . import views


urlpatterns = [
    path('', views.vswPortfolio, name='home'),
    path('project/<str:pk>/', views.vswProject, name='project'),
    path('contact/', views.vswContact, name='contact'),
   
]

Apologies if I have pasted too much info, I'm just never ended up posting enough in the past.

TYIA for any help


Solution

  • Here how i did it

    in settings.py +=

    EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST='smtp.gmail.com'
    EMAIL_PORT=587
    EMAIL_HOST_USER=''
    EMAIL_HOST_PASSWORD=''
    EMAIL_USE_TLS= True
    EMAIL_HOST_USER='[email protected]'
    EMAIL_HOST_PASSWORD='passwordgeneratedforthisappingoogleaccounts'
    

    you have to go to your account and regístrate the app, then they give you the password

    in the view:

     from django.shortcuts import render, redirect
     from  django.urls import reverse
     from . forms import ContactForm
     from django.core.mail import EmailMessage
     from django.template.loader import render_to_string
     from django.conf import settings
    
     def contact(request):
          if request.method == 'GET':
                  form = ContactForm()
                  context = {
                      'form': form
                  }
                  return render(request, 'contact.html', context)
    
         if request.method == 'POST':
    
                  form = ContactForm(request.POST)
                  if form.is_valid():
                           form.save()
    
             name=request.POST['name']
             email=request.POST['email']
             subject=request.POST['subject']
             message=request.POST['message']
    
             template=render_to_string("email_template.html", {'name': name,
                  'email':email, 'subject':subject, 'message':message})
        
             mail = EmailMessage(
                 subject,
                 template,
                 settings.EMAIL_HOST_USER,
                 ['[email protected]']
        )
    
        
    
        mail.send()
            
        return redirect(reverse('contact')+ "?ok")
    

    and add in >templates

    email_template.html

     {{message}}
    
     {{email}}
    
     {{name}}