python - 将 Django 电子邮件打印到控制台时出现问题

标签 python python-3.x django-forms django-views django-2.0

我不确定我的逻辑有什么问题,但是当我提交表单时,它会在浏览器中呈现 Httpresponse,但不会将电子邮件发布到控制台。我希望 View 功能能够成功打印到控制台。稍后我可能会实现 sendgrid 。在我开始深入研究之前,我只想运行成功的控制台打印!谢谢。

控制台输出:

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 包括:

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

查看.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=['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93feeaf6fef2fafff2f7f7e1f6e0e0d3f4fef2faffbdf0fcfe" rel="noreferrer noopener nofollow">[email protected]</a>'],
            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, })

表单.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 %}

最佳答案

作为第一次 Django 应用程序创建者,我正在向后端发送电子邮件,这是错误的。只需添加:

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

到settings.py......(很多文档只是指向实现这些行)

即使您只是像我想的那样发布到后端,您仍然需要 SMTP 来发送电子邮件内容。 (在将网站投入生产之前测试电子邮件是否成功提交)。

SMTP 选项:
我看到了几个不同的 SMTP 选项。谷歌为我工作是为了测试目的。我计划在投入生产后切换到 Sendgrid。我还没有使用 Sendgrid 的原因是因为我还没有注册域名。使用 sendgrid 进行 SMTP 的要求是拥有注册域,但我还没有。

那么我在项目中添加了什么才能使 Google SMTP 电子邮件发送到控制台后端?
设置.py

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f72667a727e76737e7b7b6d7a6c6c5f78727e7673317c7072" rel="noreferrer noopener nofollow">[email protected]</a>'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

完成此操作后,登录您的 Gmail 帐户,转至:我的帐户>设置>登录和安全
打开允许不太安全的应用程序。
作为我研究中的旁注,我发现使用 google SMTP 进行这样的离线测试是可以的,但在生产中使用它是非法的。将网站投入生产后,您必须使用不同的 SMTP 服务,例如 SendGrid。此外,您还需要确保删除 EMAIL_BACKEND,因为正如 jpmc26 指出的那样,您不希望将电子邮件数据记录在生产环境中。

关于python - 将 Django 电子邮件打印到控制台时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49697705/

相关文章:

python - django rest framework 没有身份验证没有权限

java - 使用StanfordCoreNLPServer将props(属性)从Java转换为Python3

python - django 如何通过用户状态更改 __str__ 标签?

python - 确定(Windows)上是否存在 PID 的快速方法?

python - 如何找到图像中物体的中心和角度?

python - 如何在 python http.server 中同时提供文件夹和处理 POST 请求

python - 无法将图像上传到Django项目,获取Form对象没有属性 'save'

django - 使用 Django Forms 或 Django Floppyforms 显示网格单选表单

python - 当 QuerySet 传递给上下文处理器时,Django 执行相同的查询 5 次

python-3.x - "TypeError: a bytes-like object is required, not ' 海峡 '"。我怎样才能解决这个问题?