【问题标题】:django send contact form to email raise errordjango 将联系表发送到电子邮件引发错误
【发布时间】:2016-06-11 09:18:07
【问题描述】:

我想向我的 gmail 发送联系表格。

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', 'noreply@example.com'),
            ['mypersonalemail@gmail.com'],
        )
        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

问题出在哪里? 更多解释我使用:

  • Django 版本:1.8.2
  • Python 版本:3.4.3

【问题讨论】:

  • 问题几乎肯定出在与邮件服务器的连接上。您应该显示您的电子邮件设置。
  • 对不起,我问了,但 django 文件中的电子邮件设置在哪里?我的意思是它在 django 中的目录路径在哪里?
  • 有时 gmail 会阻止连接,假设它不是用户,尤其是来自云服务器的连接。几个小时后,他们会向您发送一封电子邮件。

标签: python django email contact-form


【解决方案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'

【讨论】:

  • 我添加了这些: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myusername' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = 'mygmail@gmail.com' DEFAULT_TO_EMAIL = 'to电子邮件',但它提出了这个:Exception Type: SMTPAuthenticationErrorException Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8
  • 我认为错误是不言自明的 - 您没有通过 SMTP 服务器上的身份验证。您应该设置正确的用户名和密码,即您在 gmail 注册的真实用户名和密码。
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 2020-12-07
  • 2011-05-30
  • 1970-01-01
  • 2019-01-30
  • 2020-03-23
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多