Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import datetime
- import email
- import imaplib
- import mailbox
- import getpass
- import os
- import csv
- import html2text
- from tqdm import tqdm
- from xlsxwriter.workbook import Workbook
- CSI="\x1B["
- skip=0
- print('''
- < Welcome >
- ---------
- \
- \
- /\ /\
- //\\_//\\ ____
- \_ _/ / /
- / * * \ /^^^]
- \_\O/_/ [ ]
- / \_ [ /
- \ \_ / /
- [ [ / \/ _/
- _[ [ \ /_/
- ''')
- flag = 0
- while (flag == 0):
- try:
- EMAIL_ACCOUNT = input('\nEnter you username for gmail \n > ')
- PASSWORD = getpass.getpass('\nEnter you password \n > ')
- CRAWL = 'do-not-reply@amazon.in'
- mail = imaplib.IMAP4_SSL('imap.gmail.com')
- mail.login(EMAIL_ACCOUNT, PASSWORD)
- flag = 1
- except Exception as e:
- print('\n '+CSI+'1;31m'+'.::|Invalid Credentials|::.'+ CSI +'0m')
- print('''
- __________
- < Crawling >
- ----------
- \ ___
- \ .-' `'.
- / \
- | ;
- | | ___.--,
- _.._ |0) ~ (0) | _.---'`__.-( (_.
- __.--'`_.. '.__.\ '--. \_.-' ,.--'` `""`
- ( ,.--'` ',__ /./; ;, '.__.'` __
- _`) ) .---.__.' / | |\ \__..--"" """--.,_
- `---' .'.''-._.-'`_./ /\ '. \ _.-~~~````~~~-._`-.__.'
- | | .' _.-' | | \ \ '. `~---`
- \ \/ .' \ \ '. '-._)
- \/ / \ \ `=.__`~-.
- / /\ `) ) / / `"".`\
- , _.-'.'\ \ / / ( ( / /
- `--~` ) ) .-'.' '.'. | (
- (/` ( (` ) ) '-;
- ` '-; (-'
- ''')
- mail.list()
- mail.select('inbox')
- result, data = mail.search( None,'FROM "'+CRAWL+'"')
- i = len(data[0].split())
- if i==0:
- print('No mails found :(')
- exit()
- for x in tqdm(range(i)):
- latest_email_uid = data[0].split()[x]
- result, email_data = mail.fetch(latest_email_uid,"(RFC822)")
- # result, email_data = conn.store(num,'-FLAGS','\\Seen')
- # this might work to set flag to seen, if it is not already
- raw_email = email_data[0][1]
- raw_email_string = raw_email.decode('utf-8')
- email_message = email.message_from_string(raw_email_string)
- # Body details
- for part in email_message.walk():
- if part.get_content_type() == "text/html":
- body = html2text.html2text(str(part.get_payload(decode=True).decode('utf-8')))
- # if part.get_content_type() == "text/plain":
- # body = part.get_payload(decode=True).decode('utf-8')
- if "Order ID:" in body:
- file_name = "email.txt"
- output_file = open(file_name, 'w')
- output_file.write("%s" %(body))
- output_file.close()
- parseBody()
- else:
- skip = skip +1
- else:
- continue
- print("\n Converted %d of %d \n Skipped %d non related mails" %((i-skip),i,skip))
- csvtoxlsx()
- def parseBody():
- Ifile = open('email.txt', 'r')
- file_name = 'email.txt'.replace(".txt",".csv")
- Ofile = open (file_name,'a')
- global o_id,item,condition,sku,date,price,tax,fees,ship
- for line in Ifile:
- # s = line.split()
- # for i,j in enumerate(s):
- if "Order ID:" in line:
- o_id = line.split()[2]
- continue
- if "Item:" in line:
- item = line.partition(' ')[2].replace(',',' ').strip()
- continue
- # if j == "Condition:":
- # condition = line.partition(' ')[2].strip()
- # continue
- if "SKU:" in line:
- sku = line.partition(' ')[2].replace(',',' ').strip()
- continue
- if "date:" in line:
- date = line.split()[2]
- continue
- if "price:" in line:
- price = line.split()[3]
- continue
- if "Tax:" in line:
- tax = line.split()[2]
- continue
- if "fees:" in line :
- fees = line.split()[3]
- continue
- if "Shipping:" in line:
- ship =line.split()[2]
- Ofile.write("%s,%s,%s,%s,%.2f,%.2f,%.2f,%.2f,%.2f\n" %(str(o_id),item,sku,date,float(price),float(tax),float(float(price)+float(tax)),float(fees),float(ship)))
- Ofile.close
- os.remove('email.txt')
- # converting generated csv to excel
- def csvtoxlsx():
- name = input("\n\nWhat would you like to name your file? \n > ")
- file_name = name + '.xlsx'
- print('Generating %s ...' %(file_name))
- workbook = Workbook(file_name)
- worksheet = workbook.add_worksheet()
- with open('email.csv', 'rt', encoding='utf8') as f:
- reader = csv.reader(f)
- for r, row in enumerate(reader):
- for c, col in enumerate(row):
- worksheet.write(r, c, col)
- workbook.close()
- os.remove('email.csv')
- print('%s Generated' %(file_name))
Add Comment
Please, Sign In to add comment