How to auto log into gmail atom feed with Python?
Asked Answered
C

1

10

Gmail has this sweet thing going on to get an atom feed:

def gmail_url(user, pwd):
    return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom"

Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right.

url = gmail_url(settings.USER, settings.PASS)
print url
opener = urllib.FancyURLopener()
f = opener.open(url)
print f.read()

Instead of forwarding correctly, it's doing this:

>>> 
https://user:[email protected]/gmail/feed/atom
Enter username for New mail feed at mail.google.com: 

This is BAD! I shouldn't have to type in the username and password again!! How can I make it just auto-forward in python as it does in my web browser, so I can get the feed contents without all the BS?

Cirillo answered 21/11, 2009 at 23:1 Comment(0)
P
13

You can use the HTTPBasicAuthHandler, I tried the following and it worked:

import urllib2

def get_unread_msgs(user, passwd):
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm='New mail feed',
        uri='https://mail.google.com',
        user='%[email protected]' % user,
        passwd=passwd
    )
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    feed = urllib2.urlopen('https://mail.google.com/mail/feed/atom')
    return feed.read()
Poultry answered 21/11, 2009 at 23:30 Comment(2)
I'm getting 'urllib2.HTTPError: HTTP Error 401: basic auth failed', even though I am positive I have the username and password correct. Is anyone else having this problem?Sanjak
Nevermind. It's only a problem when I try to run the code from my server. When doing it on my local machine it works fine.Sanjak

© 2022 - 2024 — McMap. All rights reserved.