Python Django中QQ郵箱授權碼問題
系統及軟件版本如下:
- Ubuntu Kylin 16.04
- Python 3.5.1
- Django 1.9.7
- PyCharm Community Edition 2016.1.4
問題
在學習用Django寫一個博客的過程中,需添加一個郵件分享功能,在使用QQ郵箱發送郵件的時候碰到了問題。
在設置文件settings.py中添加以下設置:
EMAIL_HOST = 'smtp.qq.com'
EMAIL_HOST_USER = '2460490819@qq.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
使用manage.py提供的shell工具進行測試:
panzeyan@panzeyan-S400CA:~/PycharmProjects/myDjangoProject/mysite$ python3 manage.py shell
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.mail import send_mail
>>> send_mail("learn django", "step by step", "2460490819@qq.com",['2460490819@qq.com'], fail_silently=False)
拋出異常:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/shell.py", line 69, in handleself.run_shell(shell=options['interface'])
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.5/code.py", line 91, in runcodeexec(code, self.locals)
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/django/core/mail/__init__.py", line 61, in send_mail
return mail.send()
File "/usr/local/lib/python3.5/dist-packages/django/core/mail/message.py", line 292, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python3.5/dist-packages/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/usr/local/lib/python3.5/dist-packages/django/core/mail/backends/smtp.py", line 67, in open
self.connection.login(self.username, self.password)
File "/usr/lib/python3.5/smtplib.py", line 729, in login
raise last_exceptionFile "/usr/lib/python3.5/smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "/usr/lib/python3.5/smtplib.py", line 641, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')
思路和解決方法
忽略ImportError,關注SMTPAuthenticationError。猜測是QQ郵箱SMTP服務的授權問題導致發送郵件失敗。
打開異常末尾給出的鏈接:
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
QQ郵箱需使用授權碼作為專用密碼,登錄第三方客戶端,所以用原來的密碼會導致錯誤。
按照鏈接中的提示,進入QQ郵箱設置頁面,開啟SMTP服務,發短信獲取授權碼。然后在settings.py中將16位授權碼賦值給EMAIL_HOST_PASSWORD。
EMAIL_HOST_PASSWORD = 'shlvewmsheooebhd'
進入manage.py提供的shell工具進行測試:
>>> from django.core.mail import send_mail
>>> send_mail("1", "2", "2460490819@qq.com", ['2460490819@qq.com'], fail_silently=False)
1
1表示發送成功。登錄郵箱,成功收到郵件,問題解決。