Django联系表单不发送邮件内容

时间:2017-08-06 23:03:24

标签: python django django-forms contact-form

我的联系表单会向我的Gmail帐户发送电子邮件,但他们从不会有任何主题或邮件内容。我不太清楚接下来该做什么。如果需要更多代码,请告诉我。

views.py

from django.views.generic.edit import FormView

from .forms import ContactForm

try:
    from django.urls import reverse
except ImportError:  # pragma: no cover
    from django.core.urlresolvers import reverse  # pragma: no cover


class ContactFormView(FormView):
    form_class = ContactForm
    recipient_list = None
    template_name = 'contact_form/contact_form.html'

    def form_valid(self, form):
        form.save()
        return super(ContactFormView, self).form_valid(form)

    def get_form_kwargs(self):
        # ContactForm instances require instantiation with an
        # HttpRequest.
        kwargs = super(ContactFormView, self).get_form_kwargs()
        kwargs.update({'request': self.request})

        # We may also have been given a recipient list when
        # instantiated.
        if self.recipient_list is not None:
            kwargs.update({'recipient_list': self.recipient_list})
        return kwargs

    def get_success_url(self):

        return reverse('contact_form_sent')

forms.py

from django import forms
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.template import loader


class ContactForm(forms.Form):

    name = forms.CharField(max_length=100,
                           label=_(u'Your name'))
    email = forms.EmailField(max_length=200,
                             label=_(u'Your email address'))
    body = forms.CharField(widget=forms.Textarea,
                           label=_(u'Your message'))

    from_email = settings.DEFAULT_FROM_EMAIL

    recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS]

    subject_template_name = "contact_form/contact_form_subject.txt"

    template_name = 'contact_form/contact_form.txt'

    def __init__(self, data=None, files=None, request=None,
                 recipient_list=None, *args, **kwargs):
        if request is None:
            raise TypeError("Keyword argument 'request' must be supplied")
        self.request = request
        if recipient_list is not None:
            self.recipient_list = recipient_list
        super(ContactForm, self).__init__(data=data, files=files,
                                          *args, **kwargs)

    def message(self):
        """
        Render the body of the message to a string.
        """
        template_name = self.template_name() if \
            callable(self.template_name) \
            else self.template_name
        return loader.render_to_string(
            template_name, self.get_context(), request=self.request
        )

    def subject(self):
        """
        Render the subject of the message to a string.
        """
        template_name = self.subject_template_name() if \
            callable(self.subject_template_name) \
            else self.subject_template_name
        subject = loader.render_to_string(
            template_name, self.get_context(), request=self.request
        )
        return ''.join(subject.splitlines())

    def get_context(self):
        if not self.is_valid():
            raise ValueError(
                "Cannot generate Context from invalid contact form"
            )
        return dict(self.cleaned_data, site=get_current_site(self.request))

    def get_message_dict(self):

        if not self.is_valid():
            raise ValueError(
                "Message cannot be sent from invalid contact form"
            )
        message_dict = {}
        for message_part in ('from_email', 'message',
                             'recipient_list', 'subject'):
            attr = getattr(self, message_part)
            message_dict[message_part] = attr() if callable(attr) else attr
        return message_dict

    def save(self, fail_silently=False):
        """
        Build and send the email message.
        """
        send_mail(fail_silently=fail_silently, **self.get_message_dict())

settings.py

ALLOWED_HOSTS = ['*']

MANAGERS = [('Manager', 'email@gmail.com')]

SITE_ID = 1
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_HOST_PASSWORD = 'Password'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
FILE_UPLOAD_MAX_MEMORY_SIZE = 35000000

(它说我的代码太多而且没有足够的细节,所以我只是粘贴顶部以便错误停止出现)

我的联系表单会向我的Gmail帐户发送电子邮件,但他们从不会有任何主题或邮件内容。我不太清楚接下来该做什么。如果需要更多代码,请告诉我。

0 个答案:

没有答案