使用 imaplib 和 oauth 连接 Gmail [英] use imaplib and oauth for connection with Gmail
本文介绍了使用 imaplib 和 oauth 连接 Gmail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 Oauth 在 Python 中连接到 Gmail.现在我从谷歌得到了 xoauth.py 脚本(link), 并且生成令牌工作正常,但是我如何在另一个脚本中使用它?它将在 Django 中.
I want to use Oauth to connect to Gmail in Python. Right now I've got the xoauth.py script from Google (link), and generating a token works all fine, but how can I then use that in another script? It's going to be in Django.
现在我的脚本是这样登录的:
Right now my script logs in like this:
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("example@gmail.com", "password")
但我想要更安全的东西.
But I want something more secure.
推荐答案
这是一个使用 oauth2
的示例使用 oauth 进行身份验证的模块,取自自述文件:
Here's an example using the oauth2
module to authenticate using oauth, taken from the readme:
import oauth2 as oauth
import oauth2.clients.imap as imaplib
# Set up your Consumer and Token as per usual. Just like any other
# three-legged OAuth request.
consumer = oauth.Consumer('your_consumer_key', 'your_consumer_secret')
token = oauth.Token('your_users_3_legged_token',
'your_users_3_legged_token_secret')
# Setup the URL according to Google's XOAUTH implementation. Be sure
# to replace the email here with the appropriate email address that
# you wish to access.
url = "https://mail.google.com/mail/b/your_users_email@gmail.com/imap/"
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
# This is the only thing in the API for impaplib.IMAP4_SSL that has
# changed. You now authenticate with the URL, consumer, and token.
conn.authenticate(url, consumer, token)
# Once authenticated everything from the impalib.IMAP4_SSL class will
# work as per usual without any modification to your code.
conn.select('INBOX')
print conn.list()
比使用 xoauth
简洁得多.
这篇关于使用 imaplib 和 oauth 连接 Gmail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文