Skip to main content
 首页 » 编程设计

python之Django SMTP [Errno 111] 连接被拒绝

2025年01月19日40bhlsheji

我正在尝试使用 django 和 sendgrid SMTP 服务器从网络应用程序发送电子邮件。它在本地运行良好,但是当我尝试在 pythonanywhere 上使用它时,我得到了

error: [Errno 111] Connection refused 

相关 View 的代码是

def contact(request): 
    if request.method == 'POST': 
        form = EmailForm(request.POST) 
 
        if form.is_valid(): 
            mail = form.cleaned_data 
 
            send_mail( 
                'Automated Enquiry', 
                'A user is interested in part ' + mail['part'] + '.Their message: ' + mail['msg'], 
                mail['email'], 
                ['myemail@gmail.com'], 
                fail_silently = False, 
            ) 
 
            return render(request, 'manager/error.html', {'msg': "Thanks, we will be in touch as soon as possible"}) 
 
    else: 
        part = request.GET.get('part', '') 
        form = EmailForm() 
 
    return render(request, 'manager/contact.html', {'form': form, 'part':part})     

在我的 setting.py 中:

EMAIL_HOST = 'smtp.sendgrid.net' 
EMAIL_HOST_USER = 'myuser' 
EMAIL_HOST_PASSWORD = 'mypassword' 
EMAIL_PORT = 587 
EMAIL_USE_TLS = True 

它在控制台上也不起作用。 任何帮助将不胜感激。

请您参考如下方法:

PythonAnywhere 上的免费用户限制互联网访问 whitelist的站点,并且只允许使用 HTTP/HTTPS 协议(protocol),因此您无法从免费帐户建立到 sendgrid 的 SMTP 连接。

您可以从免费帐户使用 gmail,而 pythonanywhere 有 instructions here .

或者您可以切换到使用 sandgrid HTTP api:https://sendgrid.com/docs/Integrate/Frameworks/django.html