Get the attachment from a specific person in unread mail in python

Viewed 148

so i found some code on the web but i didn't find what i seek: here is what i've improved but i still cannot get the attachement from the 2 conditions mentionned in the title. Can someone help me ? I also use Imbox because i didn't found something better. Thank !

import os
from imbox import Imbox # pip install imbox
import traceback
from pathlib import Path

host = "imap.gmail.com"
download_folder = "/home/pi/download/folder"
allowed_email = "email-allowed.txt"
path = '/home/pi/eink_picture_frame'
pwfile = Path(path+"/maillogin.pwd")   # define file with username and password for the mail account

if pwfile.is_file():
    with open(pwfile,"r") as pf:
        pw_lines = [line.rstrip('\n') for line in pf]
    username = pw_lines[0]
    password = pw_lines[1]
else:
    print("Please provide login information in file 'maillogin.pwd'!\nFirst line: jusername\nSecond line: password")  
    quit()

allowfile = Path(path+"/email-allowed.txt")   # define file with username and password for the mail account
if allowfile.is_file():
    with open(allowfile,"r") as af:
         email_lines = [line.rstrip('\n') for line in af]
         mymail = email_lines[0]
         emmail = email_lines[1]
else:
    print("Create a list of allowed email addresses in 'email-allowed.txt'!\nFirst line: joeshmo@aol.com\nSecond line: user@google.com")
    quit()

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)
    
mailS = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
#messages = mailS.messages() # defaults to inbox
URmail = mailS.messages(unread=True)
messages = mailS.messages()
inbox_messages_frommymail = mailS.messages(sent_from=mymail)


for (uid,message) in URmail and inbox_messages_frommymail :
    print(message)
    mailS.mark_seen(uid)# optional, mark message as read

    for (idx, attachment) in enumerate(message.attachments):
        try:
            att_fn = attachment.get('filename')
            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
                
        except:
            print(traceback.print_exc())

mailS.logout()
1 Answers

you need to combine both filters to one, and it will filter both inbox_messages_frommymail = mailS.messages(sent_from=mymail,unread=True)

Related