2011-03-04 12 views
8

Quiero usar Oauth para conectarme a Gmail en Python. En este momento tengo el script xoauth.py de Google (link), y la generación de un token funciona bien, pero ¿cómo puedo usar eso en otro script? Va a estar en Django.use imaplib y oauth para la conexión con Gmail

En este momento mi script registra en este aspecto:

m = imaplib.IMAP4_SSL("imap.gmail.com") 
m.login("[email protected]", "password") 

Pero quiero algo más seguro.

Respuesta

11

Aquí hay un ejemplo usando el oauth2 module para autenticar mediante OAuth, tomada desde el 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/[email protected]/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() 

Un poco más limpio que el uso de xoauth.

+0

Hola, Bellota, soy nuevo en oauth2 y imaplib , y tengo algunas preguntas ahora, ¿puede responderlas en: http://stackoverflow.com/questions/17976626/oauth2-and-imap-connection-with-gmail – Cacheing

+1

No entiendo dónde "your_users_3_legged_token" y "your_users_3_legged_token_secret" "proceden de:/ – daveoncode

3

Aquí hay un ejemplo de conexión a IMAP usando las rutinas presentes en el xoauth.py de Google. Emitirá cierta información de depuración, por lo que es probable que desee cambiar al uso del paquete oauth para una aplicación real. Al menos esto debería empezar:

import imaplib 
import random 
import time 

import xoauth 

MY_EMAIL = '[email protected]' 
MY_TOKEN = # your token 
MY_SECRET = # your secret 

def connect(): 
    nonce = str(random.randrange(2**64 - 1)) 
    timestamp = str(int(time.time())) 

    consumer = xoauth.OAuthEntity('anonymous', 'anonymous') 
    access = xoauth.OAuthEntity(MY_TOKEN, MY_SECRET) 
    token = xoauth.GenerateXOauthString(
     consumer, access, MY_EMAIL, 'imap', MY_EMAIL, nonce, timestamp) 

    imap_conn = imaplib.IMAP4_SSL('imap.googlemail.com') 
    imap_conn.authenticate('XOAUTH', lambda x: token) 
    imap_conn.select('INBOX') 

    return imap_conn 

connect() 
+0

Esto funciona de hecho, gracias. ¿Cómo lo haría con el paquete Oauth? – HankSmackHood

+0

Puede continuar usando xoauth tal cual, si puede tolerar las instrucciones de impresión o simplemente extraerlas de su copia local. No he usado oauth personalmente, pero me imagino que la API es similar. Hay un ejemplo en el repositorio de oauth: [oauth client example] (http://oauth.googlecode.com/svn/code/python/oauth/example/client.py) – samplebias

3

Google tiene un buen código de ejemplo para hacer OAuth2 and IMAP. También asegúrese de que su alcance sea correcto.

'scope': 'https://mail.google.com/' 
'access_type': 'offline' 

abajo es del ejemplo de código de Google ejemplo

import base64 
import imaplib 

my_email = "[email protected]" 
access_token = "" #Oauth2 access token 

auth_string = GenerateOAuth2String(my_email, access_token, base64_encode=False) 
TestImapAuthentication(my_email, auth_string) 


def TestImapAuthentication(user, auth_string): 
    """Authenticates to IMAP with the given auth_string. 

    Prints a debug trace of the attempted IMAP connection. 

    Args: 
    user: The Gmail username (full email address) 
    auth_string: A valid OAuth2 string, as returned by GenerateOAuth2String. 
     Must not be base64-encoded, since imaplib does its own base64-encoding. 
    """ 
    print 
    imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') 
    imap_conn.debug = 4 
    imap_conn.authenticate('XOAUTH2', lambda x: auth_string) 
    imap_conn.select('INBOX') 


def GenerateOAuth2String(username, access_token, base64_encode=True): 
    """Generates an IMAP OAuth2 authentication string. 

    See https://developers.google.com/google-apps/gmail/oauth2_overview 

    Args: 
    username: the username (email address) of the account to authenticate 
    access_token: An OAuth2 access token. 
    base64_encode: Whether to base64-encode the output. 

    Returns: 
    The SASL argument for the OAuth2 mechanism. 
    """ 
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) 
    if base64_encode: 
    auth_string = base64.b64encode(auth_string) 
    return auth_string 
+0

Google proporciona ejemplos de OAuth 1 y 2. Su API de OAuth 1 está depreciada y no puedo hacer que funcione con django-social-auth. Lo anterior, que es OAuth 2, funciona bien con django-social-auth. –

Cuestiones relacionadas