使用imaplib和oauth来连接Gmail [英] use imaplib and oauth for connection with Gmail

查看:191
本文介绍了使用imaplib和oauth来连接Gmail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Oauth以Python连接到Gmail。现在我已经从Google获得了xoauth.py脚本(链接) ,并生成一个令牌工程都很好,但是如何才能在另一个脚本中使用它?这将是在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屋!

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