Guest User

Untitled

a guest
Jun 24th, 2018
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.78 KB | None | 0 0
  1. import datetime
  2. import email
  3. import imaplib
  4. import mailbox
  5. import getpass
  6. import os
  7. import csv
  8. import html2text
  9. from tqdm import tqdm
  10. from xlsxwriter.workbook import Workbook
  11.  
  12. CSI="\x1B["
  13. skip=0
  14. print('''
  15. < Welcome >
  16. ---------
  17. \
  18. \
  19. /\ /\
  20. //\\_//\\ ____
  21. \_ _/ / /
  22. / * * \ /^^^]
  23. \_\O/_/ [ ]
  24. / \_ [ /
  25. \ \_ / /
  26. [ [ / \/ _/
  27. _[ [ \ /_/
  28. ''')
  29. flag = 0
  30. while (flag == 0):
  31. try:
  32. EMAIL_ACCOUNT = input('\nEnter you username for gmail \n > ')
  33. PASSWORD = getpass.getpass('\nEnter you password \n > ')
  34. CRAWL = 'do-not-reply@amazon.in'
  35. mail = imaplib.IMAP4_SSL('imap.gmail.com')
  36. mail.login(EMAIL_ACCOUNT, PASSWORD)
  37. flag = 1
  38. except Exception as e:
  39. print('\n '+CSI+'1;31m'+'.::|Invalid Credentials|::.'+ CSI +'0m')
  40.  
  41. print('''
  42. __________
  43. < Crawling >
  44. ----------
  45. \ ___
  46. \ .-' `'.
  47. / \
  48. | ;
  49. | | ___.--,
  50. _.._ |0) ~ (0) | _.---'`__.-( (_.
  51. __.--'`_.. '.__.\ '--. \_.-' ,.--'` `""`
  52. ( ,.--'` ',__ /./; ;, '.__.'` __
  53. _`) ) .---.__.' / | |\ \__..--"" """--.,_
  54. `---' .'.''-._.-'`_./ /\ '. \ _.-~~~````~~~-._`-.__.'
  55. | | .' _.-' | | \ \ '. `~---`
  56. \ \/ .' \ \ '. '-._)
  57. \/ / \ \ `=.__`~-.
  58. / /\ `) ) / / `"".`\
  59. , _.-'.'\ \ / / ( ( / /
  60. `--~` ) ) .-'.' '.'. | (
  61. (/` ( (` ) ) '-;
  62. ` '-; (-'
  63. ''')
  64.  
  65. mail.list()
  66. mail.select('inbox')
  67. result, data = mail.search( None,'FROM "'+CRAWL+'"')
  68. i = len(data[0].split())
  69.  
  70. if i==0:
  71. print('No mails found :(')
  72. exit()
  73.  
  74.  
  75. for x in tqdm(range(i)):
  76. latest_email_uid = data[0].split()[x]
  77. result, email_data = mail.fetch(latest_email_uid,"(RFC822)")
  78. # result, email_data = conn.store(num,'-FLAGS','\\Seen')
  79. # this might work to set flag to seen, if it is not already
  80. raw_email = email_data[0][1]
  81. raw_email_string = raw_email.decode('utf-8')
  82. email_message = email.message_from_string(raw_email_string)
  83.  
  84. # Body details
  85. for part in email_message.walk():
  86. if part.get_content_type() == "text/html":
  87. body = html2text.html2text(str(part.get_payload(decode=True).decode('utf-8')))
  88. # if part.get_content_type() == "text/plain":
  89. # body = part.get_payload(decode=True).decode('utf-8')
  90. if "Order ID:" in body:
  91. file_name = "email.txt"
  92. output_file = open(file_name, 'w')
  93. output_file.write("%s" %(body))
  94. output_file.close()
  95. parseBody()
  96. else:
  97. skip = skip +1
  98. else:
  99. continue
  100. print("\n Converted %d of %d \n Skipped %d non related mails" %((i-skip),i,skip))
  101. csvtoxlsx()
  102.  
  103. def parseBody():
  104. Ifile = open('email.txt', 'r')
  105. file_name = 'email.txt'.replace(".txt",".csv")
  106. Ofile = open (file_name,'a')
  107. global o_id,item,condition,sku,date,price,tax,fees,ship
  108. for line in Ifile:
  109. # s = line.split()
  110. # for i,j in enumerate(s):
  111. if "Order ID:" in line:
  112. o_id = line.split()[2]
  113. continue
  114. if "Item:" in line:
  115. item = line.partition(' ')[2].replace(',',' ').strip()
  116. continue
  117. # if j == "Condition:":
  118. # condition = line.partition(' ')[2].strip()
  119. # continue
  120. if "SKU:" in line:
  121. sku = line.partition(' ')[2].replace(',',' ').strip()
  122. continue
  123. if "date:" in line:
  124. date = line.split()[2]
  125. continue
  126. if "price:" in line:
  127. price = line.split()[3]
  128. continue
  129. if "Tax:" in line:
  130. tax = line.split()[2]
  131. continue
  132. if "fees:" in line :
  133. fees = line.split()[3]
  134. continue
  135. if "Shipping:" in line:
  136. ship =line.split()[2]
  137. 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)))
  138. Ofile.close
  139. os.remove('email.txt')
  140.  
  141. # converting generated csv to excel
  142. def csvtoxlsx():
  143. name = input("\n\nWhat would you like to name your file? \n > ")
  144. file_name = name + '.xlsx'
  145. print('Generating %s ...' %(file_name))
  146. workbook = Workbook(file_name)
  147. worksheet = workbook.add_worksheet()
  148. with open('email.csv', 'rt', encoding='utf8') as f:
  149. reader = csv.reader(f)
  150. for r, row in enumerate(reader):
  151. for c, col in enumerate(row):
  152. worksheet.write(r, c, col)
  153. workbook.close()
  154. os.remove('email.csv')
  155. print('%s Generated' %(file_name))
Add Comment
Please, Sign In to add comment