用django发送电子邮件

时间:2019-01-26 12:20:09

标签: python django

我正在使用Django构建一个应用程序,并且我已经在该应用程序上构建了联系表单,该表单允许用户通过发送电子邮件进行联系。一切正常,但问题是,在收到的电子邮件中,发件人电子邮件未显示在发件人:发件人电子邮件中,而是在应用程序设置中显示了电子邮件。EMAIL_HOST_USER显示在发件人:shopvoomhelpdesk@gmail.com和发件人:shopvoomhelpdesk @ gmail中。 com。 我已经尝试调试问题,但不知道是什么原因引起的。

这是我在views.py中的代码


 def contact(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            try:
                names = form.cleaned_data['names']
                email = form.cleaned_data['email']
                print(email)
                subject = form.cleaned_data['subject'] 
                message = form.cleaned_data['message']
                message_body = f'Names: {names} \n {message}'
                send_mail(
                    subject, 
                    message_body, 
                    email,
                    [settings.EMAIL_HOST_USER], 
                    fail_silently=True
                )
                return render(request, 'sunyata/success.html')
            except Exception as e:
                context['form'] = EmailForm(request.POST)
                context['error'] = 'Unable to send message, it might be due to spelling error in\
                                        email check your email and resend again'
                return render(request, 'sunyata/success.html', context)
        else:
            form = EmailForm(request.POST)
            context['form'] = form
            return render(request, 'sunyata/contact.html', context)
    else:
        context['form'] = EmailForm()
        return render(request, 'sunyata/contact.html', context)

forms.py

from django import forms

class EmailForm(forms.Form):
    names = forms.CharField(label='Names',widget=forms.TextInput(attrs={'class':'form-control',
        'placeholder':"Enter your names"})) 
    email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class':'form-control',
        'placeholder':'Enter your email'}))
    subject = forms.CharField(label='Subject',widget=forms.TextInput(attrs={'class':'form-control',
        'placeholder':"Enter email subject"})) 
    message = forms.CharField(label='Message', widget=forms.Textarea(attrs={'class':'form-control',
               'placeholder':'Enter your message','rows':"4"}))


settings.py

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'shopvoomhelpdesk@gmail.com'
EMAIL_HOST_PASSWORD ='emailpassword'
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

1 个答案:

答案 0 :(得分:0)

您做错了而不是这样做:

send_mail(subject, message_body, email, [settings.EMAIL_HOST_USER], fail_silently=True)

应该是这样:

send_mail(subject, message_body, settings.EMAIL_HOST_USER, [email], fail_silently=True)

docssender应该是第一个参数,然后是receiver(s)

EMAIL_HOST_USER是发送者(发件人),email是接收者(发件人)。