2016-02-28 108 views
1

我想发送一个联系表格到我的Gmail。django发送联系表格到电子邮件引发错误

views.py:

def contact(request): 
errors = [] 
if request.method == 'POST': 
    if not request.POST.get('subject', ''): 
     errors.append('Enter a subject.') 
    if not request.POST.get('message', ''): 
     errors.append('Enter a message.') 
    if request.POST.get('email') and '@' not in request.POST['email']: 
     errors.append('Enter a valid e-mail address.') 
    if not errors: 
     send_mail(
      request.POST['subject'], 
      request.POST['message'], 
      request.POST.get('email', '[email protected]'), 
      ['[email protected]'], 
     ) 
     return HttpResponseRedirect('/contact/thanks/') 
return render(request, 'contact_form.html', 
    {'errors': errors}) 

contact_form.html:

</head> 
<body> 
<div> 
<h1>Contact us</h1> 

{% if errors %} 
    <ul> 
     {% for error in errors %} 
     <li>{{ error }}</li> 
     {% endfor %} 
    </ul> 
{% endif %} 

<form action="/contact/" method="post">{% csrf_token %}{% csrf_token %} 
    <p>Subject: <input type="text" name="subject"></p> 
    <p>Your e-mail (optional): <input type="text" name="email"></p> 
    <p>Message: <textarea name="message" rows="10" cols="50"> </textarea></p> 
    <input type="submit" value="Submit"> 
</form> 
</div> 
</body> 
</html> 

但是,当我提交表单它提出这个错误:

Exception Type:  ConnectionRefusedError 
Exception Value: [Errno 111] Connection refused 
Exception Location: /usr/lib/python3.4/socket.py in create_connection, line 503 

问题出在哪里? 更多explanationm我用:

  • Django的版本:1.8.2
  • Python版本:3.4.3
+2

问题几乎可以肯定地发生在与邮件服务器的连接上。你应该显示你的电子邮件设置。 –

+0

对不起,我问,但django文件中的电子邮件设置在哪里?我的意思是django中的目录路径在哪里? – niloofar

+0

有时gmail阻止连接,假设它不是用户,特别是来自云服务器。他们会在几个小时后向您发送一封电子邮件。 –

回答

1

应设置在settings.py文件正确的连接设置为gmail:

EMAIL_USE_TLS = True 
EMAIL_HOST = 'smtp.gmail.com' 
EMAIL_PORT = 587 
EMAIL_HOST_USER = 'your gmail account' 
EMAIL_HOST_PASSWORD = 'your gmail account password' 
DEFAULT_FROM_EMAIL = 'your gmail account' 
DEFAULT_TO_EMAIL = 'to email' 
+0

我添加这些: EMAIL_USE_TLS =真 EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '名为myUsername' EMAIL_HOST_PASSWORD = '输入mypassword' DEFAULT_FROM_EMAIL = '[email protected]' DEFAULT_TO_EMAIL ='电子邮件” 但它提出了这个: '异常类型:\t SMTPAuthenticationError' '异常值:\t(535,b'5.7.8用户名和密码不被接受,了解更多\ n5.7.8' – niloofar

+0

我想错误是不言自明的 - 你没有在SMTP服务器上通过验证uld设置正确的用户名和密码,这是你在gmail上注册的真实用户名和密码。 – chem1st