0

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))
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Erik hoeven
  • 1,442
  • 6
  • 26
  • 41
  • Could you please add rest of the code? looks like the variable `latest_email_uid` is your subject of the email and it is not use anywhere other than printing it on the console. – Rushikesh Gaidhani Jul 28 '20 at 11:07
  • I folowed the tutorial( see the url), but it does not work! So i did not know where the latest_email is used for! – Erik hoeven Jul 28 '20 at 11:30

1 Answers1

0

The tutorial link didn't have any code for the uid. If you didn't want it in your case you can remove the latest_email_uid variable from the print statement. Although you can get the uid using mail.uid method.

Refer: https://docs.python.org/2/library/imaplib.html

How do I print multiple email bodies with python imap?