在Django生产环境中发送电子邮件错误

时间:2019-01-14 16:12:00

标签: python django django-forms

您好,我有联系表格,用户可以在其中输入电子邮件地址,然后电子邮件将在本地发送。但是,当我在生产环境中使用此代码时,它将在Django中给出此类异常。

Exception Type: OSError at /contact-us/
Exception Value: [Errno 101] Network is unreachable

settings.py中,我已使用此代码发送电子邮件

DEBUG = True
ALLOWED_HOSTS = ['*']

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my_email_address'
EMAIL_HOST_PASSWORD = 'my_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

forms.py的代码

class ContactForm(forms.ModelForm):

    class Meta:
        model = Consulting
        #fields = ['email']
        fields = '__all__'

        widgets = {
            'email': forms.TextInput(attrs={'class': 'form-control form-control-lg'}), 
            'name': forms.TextInput(attrs={'class': 'form-control form-control-lg'}), 
            'content': forms.TextInput(attrs={'class': 'form-control form-control-lg textarea-autosize'}), 
        }


        def clean_email(self):
            email = self.cleaned_data.get('email')

            return email 

views.py编写的代码

def contact_page(request):
    contactform = ContactForm(request.POST or None)

    if contactform.is_valid():
        instance = contactform.save(commit=False)
        if Consulting.objects.filter(email=instance.email).exists():
            messages.warning(request, 'Your Email Is Already Exists', "alert alert-warning alert-dismissible")
            print("This Email Is  Already Registered")
        else:
            instance.save()
            messages.success(request, 'Thanks For The contact.', "alert alert-success alert-dismissible")

            subject = "Thankyou for joining our newsletter"
            from_email = settings.EMAIL_HOST_USER
            to_email = [instance.email]
            signup_message = """ welcome to devdap contact """
            send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=signup_message, fail_silently=False)

    context = {
        'form':  contactform 
    }

    return render(request, "pages/contact_us.html", context)

1 个答案:

答案 0 :(得分:0)

您的提供商很可能阻塞了用于发送电子邮件的端口。它也可能是由本地网络规则引起的(如果使用的是Linux,请查看Activity规则,看看是否有任何传出的通信阻塞了这些规则。)