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表示发送成功。登录邮箱,成功收到邮件,问题解决。