Skip to content

Instantly share code, notes, and snippets.

@maheshwarip
Last active February 27, 2018 08:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maheshwarip/208b60fea920ccd768bd2ebfdbef296f to your computer and use it in GitHub Desktop.
Save maheshwarip/208b60fea920ccd768bd2ebfdbef296f to your computer and use it in GitHub Desktop.
SimpleMoney email reading code
def get_gmail_messages_ind(access_token):
authorization = "Bearer "+access_token
headers = {'Authorization': authorization}
end_date = datetime.date.today() + datetime.timedelta(days=1)
end_date = date_tomorrow.strftime('%Y/%m/%d')
start_date = datetime.date.today() - datetime.timedelta(days=730)
start_date = date_yesterday.strftime('%Y/%m/%d')
# Getting the messages from RTAs, AMCs and depositories:
query = '{from:cams from:camsonline from:karvy from:sundaram from:sundarammutual from:franklin from:nsdl from:cdslstatement from:principalindia from:quantum from:edelweiss from:nse from:bse} after:'+date_yesterday+" before:"+date_tomorrow
params = {'q': query}
url = 'https://www.googleapis.com/gmail/v1/users/' + "me" + '/messages'
r = requests.get(url,headers=headers, params=params)
try:
message_list = r.json()['messages']
except KeyError:
# This indicates that no messages were downloaded
return False
for message in message_list:
message_url = url + '/'+message['id']
r2 = requests.get(message_url,headers=headers)
payload_headers = r2.json()['payload']['headers']
snippet = r2.json()['snippet']
if ("No transactions have been done during" in snippet):
# This means no transactions were found.
return False
# For the attachments:
try:
parts = r2.json()['payload']['parts']
except KeyError:
# Indicating that there were no attachments
continue
for part in parts:
if part['filename']!="":
# This requests all the attachments in the current message:
attachment_id = part['body']['attachmentId']
attachment_url = message_url+'/attachments/'+attachment_id
r3 = requests.get(attachment_url, headers=headers)
resp = r3.json()
# Parsing the data and writing as a PDF:
file_data = base64.urlsafe_b64decode(resp['data'].encode('UTF-8'))
path = './pdf_results/'+part['filename']
f = open(path,'w')
f.write(file_data)
f.close()
send_to_queue(path)
# This means all the messages were looped through unssuccessfully:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment