2

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 %}
Ryan L
  • 39
  • 1
  • 5
  • It's not clear what you're trying to achieve or why you expect that behavior to work out of the box. *What* exactly do you want in the console? You have a POST with data most likely in the body, rather than as query parameters (meaning it's not part of the URL that's printed). And you send an e-mail over SMTP, not through another request to the web server. So why would you expect any of that to be printed to the console? Also, why in particular do you want it in the console? You probably don't want this data logged in production. – jpmc26 Apr 06 '18 at 19:09
  • I just wanted to test to see if it will actually send emails before I send it into production. I read that when you include the (EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend') in settings.py it will print the email to the console where your server is running without having to use smtp. I want to simply make sure the contact form works before I went through with implementing a SMTP. Do you suggest I just go straight into trying to implementing smtp and seeing if the emails work then?reference post: https://stackoverflow.com/questions/47085943/django-contact-form-sending-email – Ryan L Apr 06 '18 at 20:00

2 Answers2

1

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.

Ryan L
  • 39
  • 1
  • 5
1

The accepted answer is not correct. It says "You still need an SMTP to send the email contents" when using the console back end. But the whole point of the console back-end is that it is useful withOUT SMTP.

If you are using the console back end and not seeing output, the likely reason is that you haven't specified valid recipient and sender addresses: to=['a@b.com'], from_email="c@d.com" ...

Add those and you'll see the email in the console, even without SMTP settings. Remember that to= is always a list, not a single address!

shacker
  • 14,712
  • 8
  • 89
  • 89
  • True: you don't need SMTP, you could leave it blank, so that it falls back to the Django default `EMAIL_HOST = 'localhost'` when you send email to the console. – Domenico Spidy Tamburro Nov 25 '22 at 10:00