【问题标题】:only getting SMTPServerDisconnected: please run connect() first when calling on server只获取 SMTPServerDisconnected:调用服务器时请先运行 connect()
【发布时间】:2021-08-30 04:12:30
【问题描述】:

我最近启用了以 Sendgrid smtp 作为后端的 Django 电子邮件发送功能

这是我的电子邮件设置:

#AUTO SEND EMAIL
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'the_sendgrid_key'
EMAIL_PORT = 587

在我的一个 api 中得到以下代码:

student = request.user
subject = 'test',
text_content = 'test'
email = EmailMultiAlternatives(subject, text_content, os.environ.get('DEFAULT_FROM_EMAIL'), to=[student.email])
email.attach_alternative(html_content, "text/html")
email.send()

在本地开发过程中,每当我调用 api 时,电子邮件都会发送并且我正常收到它

但是当我在服务器上调用 api 时,它不断返回以下错误:

SMTPServerDisconnected: please run connect() first (Most recent call last)
File /root/study/api/views/views.py line 1470 in post args locals
email.send()
File /usr/lib/python3.8/smtplib.py line 753 in starttls args locals
self.ehlo_or_helo_if_needed()
File /usr/lib/python3.8/smtplib.py line 604 in ehlo_or_helo_if_needed args locals
if not (200 <= self.ehlo()[0] <= 299):
File /usr/lib/python3.8/smtplib.py line 444 in ehlo args locals
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File /usr/lib/python3.8/smtplib.py line 371 in putcmd args locals
self.send(str)
File /usr/lib/python3.8/smtplib.py line 363 in send args locals
raise SMTPServerDisconnected('please run connect() first')
SMTPServerDisconnected: please run connect() first

在查找此错误后,只有有关错误电子邮件设置的答案,但我检查了电子邮件设置完全正确(因为我在本地收到电子邮件)

另一个奇怪的事情是当我在服务器上运行python manage.py shell 并直接调用email.send() 方法时没有弹出错误并且我收到了电子邮件。

我一直在寻找解决方案一个星期了,似乎无法找到为什么只有在调用包含该方法的api时才会弹出错误,希望有类似问题的人可以帮助我解决

更新: 我尝试按照 cmets 中的建议在视图中手动打开和关闭:

from django.core.mail import EmailMultiAlternatives, get_connection, EmailMessage

connection = get_connection()

# Manually open the connection
connection.open()

# Construct an email message that uses the connection
email1 = EmailMessage(
    subject,
    text_content,
    os.environ.get('DEFAULT_FROM_EMAIL'),
    to=[student.email],
    connection=connection,
)
email1.send() # Send the email
connection.close()

但仍然出现相同的 connect() 错误:

SMTPServerDisconnected: please run connect() first (Most recent call last)
File /root/study/api/views/views.py line 1474 in post args locals
connection.open()
Show 1 non-project frame
File /usr/lib/python3.8/smtplib.py line 753 in starttls args locals
self.ehlo_or_helo_if_needed()
File /usr/lib/python3.8/smtplib.py line 604 in ehlo_or_helo_if_needed args locals
if not (200 <= self.ehlo()[0] <= 299):
File /usr/lib/python3.8/smtplib.py line 444 in ehlo args locals
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File /usr/lib/python3.8/smtplib.py line 371 in putcmd args locals
self.send(str)
File /usr/lib/python3.8/smtplib.py line 363 in send args locals
raise SMTPServerDisconnected('please run connect() first')
SMTPServerDisconnected: please run connect() first

更新 2:

我的服务器启用了 SSL,在带有 nginx 的 gunicorn 上运行以提供静态文件并重定向端口

gunicorn 配置:

[Unit]
Description=Gunicorn daemon for Django Project
Before=nginx.service
After=network.target

[Service]
WorkingDirectory=/root/study
ExecStart=/root/.cache/pypoetry/virtualenvs/base.django-H96T9Ltg-py3.8/bin/gunicorn --log-level=debug  --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/gunicorn/error.log --workers 5 --bind unix:/var/log/gunicorn/hoola.sock base.wsgi:application
Restart=always
SyslogIdentifier=gunicorn
User=root
Group=www-data


[Install]
WantedBy=multi-user.target

nginx 配置:

user root;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

更新 5: 来自 rollbar 错误记录的更多详细错误回溯:

SMTPServerDisconnected: please run connect() first (Most recent call last)
File /root/study/api/views/views.py line 1729 in get args locals
email.send()
get arguments
"self" "<class 'api.views.views.email_testing'>"
"request" "<class 'rest_framework.request.Request'>"
get local variables
e "<class 'smtplib.SMTPServerDisconnected'>"
email "<class 'django.core.mail.message.EmailMultiAlternatives'>"
request "<class 'rest_framework.request.Request'>"
self "<class 'api.views.views.email_testing'>"
Hide 3 non-project frames
File /root/.cache/pypoetry/virtualenvs/base.django-H96T9Ltg-py3.8/lib/python3.8/site-packages/django/core/mail/message.py line 284 in send args locals
return self.get_connection(fail_silently).send_messages([self])
send arguments
"self" <class'django.core.mail.message.EmailMultiAlternatives'>"
"fail_silently" unknown
send local variables
fail_silently false
self "<class 'django.core.mail.message.EmailMultiAlternatives'>"
File /root/.cache/pypoetry/virtualenvs/base.django-H96T9Ltg-py3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py line 102 in send_messages args locals
new_conn_created = self.open()
send_messages arguments
"self" "<class 'django.core.mail.backends.smtp.EmailBackend'>"
"email_messages [<class'django.core.mail.message.EmailMultiAlternatives'>"]
send_messages local variables
email_messages ["<class 'django.core.mail.message.EmailMultiAlternatives'>"]
self "<class 'django.core.mail.backends.smtp.EmailBackend'>"
File /root/.cache/pypoetry/virtualenvs/base.django-H96T9Ltg-py3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py line 67 in open args locals
self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile)
open arguments
"self" "<class 'django.core.mail.backends.smtp.EmailBackend'>"
open local variables
connection_params {"local_hostname": "mydomain.io"}
self "<class 'django.core.mail.backends.smtp.EmailBackend'>"
File /usr/lib/python3.8/smtplib.py line 753 in starttls args locals
starttls arguments
"self" "<class 'smtplib.SMTP'>"
"keyfile" unknown
"certfile" unknown
"context" inknown
starttls local variables
certfile null
context null
keyfile null
self "<class 'smtplib.SMTP'>"
File /usr/lib/python3.8/smtplib.py line 604 in ehlo_or_helo_if_needed args locals
if not (200 <= self.ehlo()[0] <= 299):
ehlo_or_helo_if_needed arguments
"self" "<class 'smtplib.SMTP'>"
ehlo_or_helo_if_needed arguments
self "<class 'smtplib.SMTP'>"
File /usr/lib/python3.8/smtplib.py line 444 in ehlo args locals
self.putcmd(self.ehlo_msg, name or self.local_hostname)
ehlo arguments
"self" "<class 'smtplib.SMTP'>"
"name" unknown
ehlo local variables
name ""
self "<class 'smtplib.SMTP'>"
File /usr/lib/python3.8/smtplib.py line 371 in putcmd args locals
self.send(str)
putcmd arguments
"self" "<class 'smtplib.SMTP'>"
"cmd" "ehlo"
"args" "mydomain.io"
putcmd local variables
args "mydomain.io"
cmd "ehlo"
self "<class 'smtplib.SMTP'>"
str "ehlo mydomain.io\r\n"
File /usr/lib/python3.8/smtplib.py line 363 in send args locals
raise SMTPServerDisconnected('please run connect() first')
send arguments
"self" "<class 'smtplib.SMTP'>"
"s" "ehlo mydomain.io\r\n"
send local variables
s "ehlo mydomain.io\r\n"
self "<class 'smtplib.SMTP'>"
SMTPServerDisconnected: please run connect() first

【问题讨论】:

  • 您是否尝试按照错误提示使用connect()
  • django mail 的文档在某些地方显示.open()get_connection()EmailMessage(.., connection=connection). And shell` 在许多工具/框架中试图让生活更简单,它可能会自动运行一些代码,但在正常情况下代码您必须添加一些代码才能获得相同的结果。例如,在 shell 中,您不必使用 print() 来显示结果。
  • @furas 连接错误在 django 使用的 smtp 库中,从阅读电子邮件发送的 django 文档开始,不需要运行 smtp connect()。我也使用了你提到的建议,但仍然遇到同样的错误
  • 如果它在本地计算机上工作但在服务器上不起作用,那么服务器可能会阻止连接以停止使用服务器发送垃圾邮件。一些服务器阻止访问其他服务器以阻止垃圾邮件发送者/黑客/机器人。您可以查看服务器的文档或询问服务器管理员是否阻止了对外部服务器的访问。
  • @furas 问题是,当我尝试在服务器上直接使用python manage.py shell 调用 email.send() 时,它会起作用,如果服务器阻塞,那么电子邮件直接运行也不应该失败?在这种情况下它没有。只有在 api 中才会失败

标签: python django smtp sendgrid django-email


【解决方案1】:

所以我终于找到了为什么它似乎永远无法连接,这是因为我的 gunicorn 的整个项目设置缺少 .env 文件变量。这就是为什么 EMAIL_HOST 和 EMAIL 配置在视图中运行时从不加载的原因。

我将 loadenv 添加到我的 wsgi.py 文件中,以便 gunicorn 可以加载它:

import os

from django.core.wsgi import get_wsgi_application
from dotenv import load_dotenv

load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env'))
#load env before running wsgi
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")
 
application = get_wsgi_application()

还改变了我的 gunicorn.service 运行命令的方式;

在 ExecStart 中,我从 base.wsgi:application 更改为 base.wsgi,因此它还加载了整个 dotenv 变量,而不仅仅是应用程序

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 2021-05-16
    • 1970-01-01
    • 2018-02-13
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多