Skip to content

Instantly share code, notes, and snippets.

@paruldixit
Created June 8, 2017 10:36
Show Gist options
  • Save paruldixit/7f9482dde314ee057f3643dcf7d0fed2 to your computer and use it in GitHub Desktop.
Save paruldixit/7f9482dde314ee057f3643dcf7d0fed2 to your computer and use it in GitHub Desktop.
Log in to google account and fetch unread emails using python3 and BeautifulSoup.
from bs4 import BeautifulSoup
import requests
GLOGIN_URL = 'https://mail.google.com'
GAUTH_URL = 'https://accounts.google.com/ServiceLoginAuth'
GMAIL_URL = 'https://mail.google.com/mail/u/0/'
class GoogleLogin():
def __init__(self, username, password):
self.session = requests.session()
self.username = username
self.password = password
self.loggedIn = False
def __html_doc(self, url):
return self.session.get(url).content
def __html_parser(self, html_doc):
return BeautifulSoup(html_doc, "html.parser")
def get_login_params(self, soup):
# Prepare login params
login_params = {
'Email': self.username,
'Passwd': self.password
}
for inp in soup.select("#gaia_loginform input[name]"):
if inp["name"] not in login_params:
login_params[inp["name"]] = inp["value"]
return login_params
def perform_glogin(self):
# perform google login
html_doc = self.__html_doc(url=GLOGIN_URL)
soup = self.__html_parser(html_doc=html_doc)
login_params = self.get_login_params(soup=soup)
# Login to google account
response = self.session.post(GAUTH_URL, login_params)
if response.url == GMAIL_URL:
self.loggedIn = True
else:
print("Please Enter valid username and password.")
exit()
def get_mails(self):
# Go to Gmail
if not self.loggedIn:
self.perform_glogin()
html_doc = self.__html_doc(url=GMAIL_URL)
data = soup = self.__html_parser(html_doc=html_doc)
# Go to Gmail in basic HTML:
form = data.find("form")
action = form.get('action')
post_url = GMAIL_URL + action
html = self.session.get(post_url)
gmail_doc = BeautifulSoup(html.text, 'html.parser')
return gmail_doc
def get_unread_mails(self):
# fetch unread mails
gmail_doc = self.get_mails()
form = gmail_doc.find_all("form", attrs={"name": "f"})[0]
mail_data = form.select('table.th td b')
unread_mail_list = [{'from': mail_data[i].text, 'sub': mail_data[i + 1].text, 'date': mail_data[i + 2].text, }
for i in range(0, len(mail_data), 3)]
for mail in unread_mail_list:
print(mail['from'] + '::' + mail['sub'] + '::' + mail['date'])
if __name__ == '__main__':
Glogin_obj = GoogleLogin('your_username', 'your_password')
Glogin_obj.get_unread_mails()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment