Chu*_*uie 7 python email django gmail smtp
当我尝试通过./manage.py shell发送时,发送一封电子邮件需要几分钟时间.当我在浏览器中提交表单后尝试发送用户验证电子邮件时,浏览器超时504,但最终会发送电子邮件.会发生什么事?
settings.py
...
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail@gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = os.environ.get('PASSWORD')
...
Run Code Online (Sandbox Code Playgroud)
views.py
class SignUpView(CreateView):
model = User
template_name = 'eventMap/register.html'
form_class = RegistrationForm
success_url="/"
def form_valid(self, form):
form.save()
username = form.cleaned_data['username']
email = form.cleaned_data['email']
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(salt+email).hexdigest()
key_expires = datetime.datetime.today() + datetime.timedelta(2)
#Get user by username
user=User.objects.get(username=username)
# Create and save user profile
new_profile = UserProfile(user=user, activation_key=activation_key,
key_expires=key_expires)
new_profile.save()
# Send email with activation key
email_subject = 'Account confirmation'
email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
48hours http://mywebsite.com/accounts/confirm/%s" % (username, activation_key)
send_mail(email_subject, email_body, 'myemail@gmail.com',
['mytestemail@gmail.com'], fail_silently=False)
return super(SignUpView, self).form_valid(form)
Run Code Online (Sandbox Code Playgroud)
我在这篇文章中看到类似的东西,但日志中没有提到任何关于不合格的主机名等的内容/var/log/mail.log
Jul 27 16:26:04 django postfix/qmgr[5975]: CAF7C1226F2: from=<>, size=3063, nrcpt=1 (queue active)
Jul 27 16:26:34 django postfix/smtp[12874]: connect to example.com[2606:2800:220:1:248:1893:25c8:1946]:25: Connection timed out
Jul 27 16:27:04 django postfix/smtp[12874]: connect to example.com[93.184.216.34]:25: Connection timed out
Jul 27 16:27:04 django postfix/smtp[12874]: CAF7C1226F2: to=<myemail@example.com>, relay=none, delay=368178, delays=368118/0.02/60/0, dsn=4.4.1, status=deferred (connect to example.com[93.184.216.34]:25: Connection timed out)
Run Code Online (Sandbox Code Playgroud)
C-o*_*r-E 10
我有一个类似的情况,延迟和超时是由系统尝试通过IPv6连接到gmail引起的.
这个主题在揭开神秘面纱方面很有用.
TLDR:
在主机上尝试使用telnet连接到gmail.
telnet smtp.gmail.com 587
Run Code Online (Sandbox Code Playgroud)
如果它首先尝试通过IPv6连接(并且阻塞几分钟),然后在IPv4上成功连接,那么这可能是您的问题.
解决方案:
import socket
EMAIL_HOST = socket.gethostbyname('smtp.gmail.com')
Run Code Online (Sandbox Code Playgroud)
这可以确保python从一开始就通过IPv4连接到gmail.
更好的方案:
找出您的主机无法通过IPv6连接到gmail并解决该问题的原因.也许调整防火墙规则来拒绝数据包而不是丢弃它们.