Advertisement
Guest User

Untitled

a guest
Jun 17th, 2023
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import imaplib
  2. import email
  3. from PyPDF2 import PdfFileMerger
  4. import shutil
  5. import os
  6.  
  7. # Email account credentials
  8. username = '[email protected]'
  9. password = 'your_password'
  10.  
  11. # Connect to Yahoo IMAP server
  12. imap_server = 'imap.mail.yahoo.com'
  13. imap_port = 993
  14.  
  15. # Establish connection
  16. mail = imaplib.IMAP4_SSL(imap_server, imap_port)
  17. mail.login(username, password)
  18.  
  19. # Select the "Receipts" subfolder
  20. mail.select('Receipts')
  21.  
  22. # Search for unread emails with attachments
  23. result, data = mail.search(None, '(UNSEEN)', 'HAS attachment')
  24.  
  25. attachments_to_print = [] # List to store filenames of attachments to print
  26. unread_email_nums = data[0].split()
  27.  
  28. # Iterate through unread emails with attachments
  29. for num in unread_email_nums:
  30. # Fetch email details
  31. _, msg_data = mail.fetch(num, '(RFC822)')
  32. _, msg_bytes = msg_data[0]
  33. msg = email.message_from_bytes(msg_bytes)
  34.  
  35. # Check if email has two attachments
  36. if len(msg.get_payload()) == 2:
  37. # Iterate through attachments
  38. for part in msg.walk():
  39. if part.get_content_type() == 'application/pdf':
  40. # Identify attachment with "Receipt" in filename
  41. if 'receipt' in part.get_filename().lower():
  42. # Save attachment to a file
  43. filename = part.get_filename()
  44. with open(filename, 'wb') as f:
  45. f.write(part.get_payload(decode=True))
  46. attachments_to_print.append(filename)
  47.  
  48. # Mark the email as read
  49. mail.store(num, '+FLAGS', '\\Seen')
  50.  
  51. # Close the connection
  52. mail.logout()
  53.  
  54. # Merge attachments into a single PDF file
  55. output_filename = 'receipts.pdf'
  56. pdf_merger = PdfFileMerger()
  57.  
  58. for attachment in attachments_to_print:
  59. pdf_merger.append(attachment)
  60.  
  61. pdf_merger.write(output_filename)
  62. pdf_merger.close()
  63.  
  64. # Open the merged PDF in Safari
  65. shutil.move(output_filename, 'receipts.pdf')
  66. os.system('open -a Safari receipts.pdf')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement