邮件功能在Django中不发送邮件

时间:2019-04-19 03:44:37

标签: django

我用基本的HTML标签编写了代码,例如,没有问题。邮件已正确发送。但是,当我更改其位置并且HTML标签的邮件功能不起作用时。有什么问题吗?

有效

<h1>Contact Us</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <div class="form-actions">
      <button type="submit">Send</button>
    </div>
</form>

它不起作用。

<form class="contact-form" action="" method="GET">
    {% csrf_token %}
    {% for field in form %}
    {{ field|add_class:"input" }}            
    {% endfor %}
    <button class="button" type="submit">Send</button> 
</form>

views.py

def index(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST or None)
        if form.is_valid():
            fullname = form.cleaned_data['fullname']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(fullname, message, from_email, 
                           ['gulnarnecefova1996@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('home')
    context['form'] = form
    return render(request, "index.html", context)

1 个答案:

答案 0 :(得分:1)

您所说的not working表格:

<form class="contact-form" action="" method="GET">
    {% csrf_token %}
    {% for field in form %}
    {{ field|add_class:"input" }}            
    {% endfor %}
    <button class="button" type="submit">Send</button> 
</form>

您可以看到您已经使用过method="GET"。然后在您的意见中:

def index(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST or None)
        if form.is_valid():
            fullname = form.cleaned_data['fullname']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(fullname, message, from_email, 
                       ['gulnarnecefova1996@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('home')
    context['form'] = form
    return render(request, "index.html", context)

在这里,您已使用以下代码在POST method block内部发送邮件:

    else:
        form = ContactForm(request.POST or None)
        if form.is_valid():
            fullname = form.cleaned_data['fullname']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(fullname, message, from_email, 
                       ['gulnarnecefova1996@gmail.com'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('home')

因此,在您提交表单时,它是作为get请求发送的。 get请求正在由以下代码块处理:

    if request.method == 'GET':
        form = ContactForm()

因此,邮件功能不起作用。

尝试以html形式将方法更改为post