从联系表单发送消息后,Gmail错误。的Django 2.1.5

时间:2019-01-22 14:08:47

标签: python django

我从pythonanywhere发送消息,但是将我的电子邮件作为发件人电子邮件(from_email = to_email)发送到gmail即将到来的消息。

forms.py

class ContactForm(forms.Form):
    subject = forms.CharField()
    contact_email = forms.EmailField()
    content = forms.CharField(widget=CKEditorUploadingWidget()

views.py

def contact(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['contact_email']
            content = form.cleaned_data['content']

            try:
                send_mail(subject, content, from_email, ['****@gmail.com'], )
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, 'contact.html', {'form': form})

settings.py

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '****@gmail.com'
EMAIL_HOST_PASSWORD = '****'

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

DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

已启用gmail.com的所有设置

在邮件详细信息中,我找到了真正的gmail发件人(在X-google-original-from中) 我想把它放在from_email

enter image description here

1 个答案:

答案 0 :(得分:0)

Thnx @ 9769953和@dirkgroten寻求帮助。

views.py

def contact(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            contact_name = form.cleaned_data['contact_name']
            from_email = form.cleaned_data['contact_email']
            content = form.cleaned_data['content']

            # try:
            msg = EmailMessage(subject, "От: " + from_email + ' (' + (contact_name) + ")\n\n" + content, from_email, ['****@gmail.com'])

            msg.send()

            # except BadHeaderError:
            #     return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, 'contact.html', {'form': form})