I am trying to write a Python(3.83.64-bit) which download the attachment of the emails to a file location on the Windows environment. I am using here for the instructions of the following article ( https://medium.com/@sdoshi579/to-read-emails-and-download-attachments-in-python-6d7d6b60269 )
I rewrote the code so it points to the right directory and use the credentials i needed. But after execution i received the following error:
name 'latest_email_uid' is not defined
I used the code which is put below:
#Python Modules
import logging
import email
import imaplib
import base64
import os
from datetime import datetime
from pathlib import Path
#Configurations
EMAIL = '***@*****.**'
PASSWORD = '****'
SERVER = '***.****.com'
local_path = Path("data")
# Connection settings to Database and Email Server
mail = imaplib.IMAP4_SSL(SERVER)
mail.login(EMAIL, PASSWORD)
try:
mail.select('CV')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1]
# converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
# downloading attachments
for part in email_message.walk():
# this part comes from the snipped I don't understand yet...
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
upload_file_path = local_path / fileName
if not os.path.isfile(upload_file_path) :
fp = open(upload_file_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))
except Exception as e:
print("Error with reading mail!")
print(str(e))