Django通过gmail的send_mail非常慢 [英] Django send_mail through gmail very slow

查看:95
本文介绍了Django通过gmail的send_mail非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过./manage.py shell发送邮件时,要花几分钟才能发送一封电子邮件。当我尝试在浏览器中提交表单后发送用户验证电子邮件时,浏览器会显示504超时,但最终会发送该电子邮件。

When I try send through ./manage.py shell it takes several minutes to send a single email. When I try to send a user verification email after a form submission in a browser the browser times out with a 504, but the email is eventually sent. What could be going on?

settings.py

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')   
...

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) 

我在这篇文章中遇到了类似的情况,但是日志中没有提及不合格的主机名,例如
/var/log/mail.log

I came across this post about something similar but the logs don't mention anything about an unqualified hostname etc /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)


推荐答案

类似的情况,其中延迟和超时是由系统尝试通过IPv6连接到gmail引起的。

I had a similar case where the delay and timeout were caused by the system trying to connect to gmail over IPv6.

线程有助于揭开谜团。

TLDR:

在主机上,尝试使用telnet连接到gmail。

On the host machine try using telnet to connect to gmail.

telnet smtp.gmail.com 587

如果它首先尝试通过IPv6连接(并阻塞了几分钟),然后在IPv4上成功连接,则可能是您的问题。

If it first attempts to connect over IPv6 (and blocks for a few minutes) followed by a successful connection on IPv4, then this is likely your problem.

解决方案:

import socket
EMAIL_HOST = socket.gethostbyname('smtp.gmail.com')

这可以确保python从一开始就通过IPv4连接到gmail。

This ensures that python will connect to gmail over IPv4 from the beginning.

更好的解决方案:

弄清楚为什么主机无法通过IPv6连接到gmail并解决该问题。也许调整防火墙规则以拒绝数据包而不是丢弃它们。

Figure out why your host can't connect to gmail over IPv6 and fix that issue. Perhaps adjusting firewall rules to reject packets instead of dropping them.

这篇关于Django通过gmail的send_mail非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆