pythonpython-3.xdjango-formsdjango-viewsdjango-2.0

Issues printing Django email to console


I am not sure what is wrong with my logic, but when I submit a form, it renders the Httpresponse in the browser, but doesn't post the email to the console. I want the view function to be able to print to the console successfully. Later I am going to be implementing sendgrid probably. I just wanted to run successful console prints before I started diving into that! Thanks.

Console output:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[06/Apr/2018 11:15:30] "GET /app01/contact_us/ HTTP/1.1" 200 2880
[06/Apr/2018 11:15:40] "POST /app01/contact_us/ HTTP/1.1" 200 30

settings.py includes:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

view.py

from django.shortcuts import render
from django.views import generic
from django.core.mail import EmailMessage
from django.template.loader import get_template
from django.contrib import messages

from .models import *
from .forms import ContactForm

# Create your views here.
def contact_form(request):
form_class = ContactForm

if request.method == 'POST':
    form = form_class(data=request.POST)

    if form.is_valid():
        contact_name = request.POST.get('contact_name', '')
        contact_email = request.POST.get('contact_email', '')
        contact_phone = request.POST.get('contact_phone', '')
        move_date = request.POST.get('move_date', '')
        address_from = request.POST.get('address_from', '')
        address_to = request.POST.get('address_to', '')
        contact_access = request.POST.get('contact_access', '')
        additional_information = request.POST.get('additional_information', '')
        contact_hear = request.POST.get('contact_hear', '')

        template = get_template('app01/contact_template.txt')
        context = {
            'contact_name': contact_name,
            'contact_email': contact_email,
            'contact_phone': contact_phone,
            'move_date': move_date,
            'address_from': address_from,
            'address_to': address_to,
            'contact_access': contact_access,
            'additional_information': additional_information,
            'contact_hear': contact_hear,
        }
        content = template.render(context)

        email = EmailMessage(
            'New Estimate Request',
            content,
            to=['myemailaddress@gmail.com'],
            headers = {'Reply-To': contact_email},
        )
        email.send()
        messages.success(request, 'Email successfully submitted.')
        return render(request, 'app01/contact_us.html', {'form': form_class, })

return render(request, 'app01/contact_us.html', {'form': form_class, })

forms.py

from django import forms

ACCESS_CHOICES = (
    ('1', 'No'),
    ('2', 'Yes')
)
HEAR_CHOICES = (
    ('1', 'Search Engine'),
    ('2', 'Referral'),
    ('3', 'Social Media'),
    ('4', 'Other'),
)

class ContactForm(forms.Form):
    contact_name = forms.CharField(label='Name', required=True)
    contact_email = forms.EmailField(label='E-mail', required=True)
    contact_phone = forms.CharField(label='Phone number', required=True, max_length=15)
    move_date = forms.DateField(label='Date Requested', required=False)
    address_from = forms.CharField(label='Address From', required=False)
    address_to = forms.CharField(label='Address To', required = False)
    contact_access = forms.ChoiceField(choices=ACCESS_CHOICES, label='Is there restrictive access to either address that we should be aware of? (stairs, narrow drive, etc.)')
    additional_information = forms.CharField(label='Additional Information', max_length=250, required=False)
    contact_hear = forms.ChoiceField(choices=HEAR_CHOICES, label='How did you hear about us?', required=False)

contact_us.html

{% extends 'app01/base.html' %}
{% block body %}
<form action="" method="post">
{% csrf_token %}
{{ form }}
    <input type="submit" value="submit" />
</form>
{% endblock %}

Solution

  • I was going about emailing the back end wrong as a first time Django app creator. just simply adding:

    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    

    to settings.py....(lots of documentation just point to implementing these lines)

    You still need an SMTP to send the email contents, even if you are just posting to the back-end like I wanted to. (to test for successful email submission before putting the site into production).

    SMTP options:
    I saw a few different SMTP options. Google worked for me for testing purposes. I plan on switching to Sendgrid once I go to production. The reason I am not using Sendgrid yet, is because I don't have the registered domain yet. Having a registered domain is a requirement of using sendgrid for your SMTP and I don't have mine yet.

    So what did I add to my project to make Google SMTP email to the console backend?
    Settings.py

    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'myemailaddress@gmail.com'
    EMAIL_HOST_PASSWORD = 'mypassword'
    EMAIL_USE_TLS = True
    EMAIL_PORT = 587
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
    

    After doing this, sign into you gmail account, go to: my account>settings>sign in and security
    Turn allow less secure apps ON.
    As a side note in my research, I found out that it is okay to use google SMTP for testing offline like this, but it is illegal to use it in production. You must use a different SMTP service such as SendGrid once you push your website into production. Also you would want to make sure you remove the EMAIL_BACKEND, because as jpmc26 pointed out, you don't want the email data logged in production.