Django联系表格发送电子邮件

时间:2017-11-02 23:02:36

标签: python django email contact-form

我创建了一个联系表单,在用户填写时向我发送电子邮件。一切似乎都有效,但我没有收到电子邮件。

这是我的控制台输出:

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Michael Plemmons
From: mplemmons1982@gmail.com
To: californiamikegreen@yahoo.com
Date: Thu, 02 Nov 2017 22:40:50 -0000
Message-ID: <20171102224050.12741.24539@ubuntu>

hello this is a test
-------------------------------------------------------------------------------
[02/Nov/2017 22:40:50] "POST /contact/ HTTP/1.1" 302 0
[02/Nov/2017 22:40:50] "GET /success/ HTTP/1.1" 200 36

这是views.py

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from .models import *
from .forms import contact_form
from django.core.mail import send_mail, BadHeaderError
from django.shortcuts import redirect

def contact(request):
    if request.method == 'GET':
        form = contact_form()
    else:
        form = contact_form(request.POST)
        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            contact_message = form.cleaned_data['contact_message']
            try:
                send_mail(contact_name, contact_message, contact_email, ['californiamikegreen@yahoo.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, "contact.html", {'form': form})


def success(request):
    return HttpResponse('Success! Thank you for your message.')

这是urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'contact/$',views.contact, name='contact'),
    url(r'^success/$', views.success, name='success'),
]

这是forms.py

from django import forms

from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User

class contact_form(forms.Form):
    contact_name = forms.CharField(label='Contact Name', max_length=255)
    contact_email = forms.CharField(label='Contact Email',max_length=255)
    contact_message = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

和contact.html

{% block title %}Contact - {{ block.super }}{% endblock %}

{% block content %}
<h1>Contact</h1>
<form role="form" action="" method="post">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Submit</button>
</form>
{% endblock %}

这包含在settings.py

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

我有什么遗漏才能真正转到我的电子邮箱吗?

由于

1 个答案:

答案 0 :(得分:2)

console backend,顾名思义,将电子邮件打印到控制台,不做任何其他事情。

您需要使用不同的电子邮件后端,例如[smtp backend]是默认的:

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

然后,您必须使用电子邮件提供商的设置配置EMAIL_HOST等设置。有关详细信息,请参阅the docs

如果您不想使用SMTP后端,另一个常见的选择是使用Mailgun或SendGrid之类的交易邮件提供商。其中一些服务具有免费使用级别,这对于低容量联系表单应该是足够的。 django-anymail应用支持多个交易邮件提供商。