For loop only shows the first object

2024/7/6 22:03:13

I have a code that loops through a list of mails, but it is only showing the first result, even though there are also other matches.

The other results require me to loop over the mails again only to return the value.

mail = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = mail.GetDefaultFolder(6).Folders["Trial"]
df = pd.read_excel(r"C://User//Asus//Test//Test.xlsx", sheet_name = 'Sheet1')
mail = df.iloc[:,0].tolist() #this is the list of emails i.e. ends with gmail.com
processed = mail.GetDefaultFolder(6).Folders["Trial"].Folders["Done"]
msg = inbox.Items.GetFirst()
add = msg.SenderEmailAddressfor attch in msg.Attachments:if any([add.endswith(m) for m in mail]) and attch.FileName[-3:] != 'png':fname = attch.FileNamedir = "C://User//Asus//Output//"tempdir = os.path.join(dir, fname)attch.SaveAsFile(tempdir)
msg.Move(processed) #move the emails that completed processed to another folder

Updated Codes V1

I had revised the codes according to the suggestion, but with bad luck, now it only loops through the first two email..

mail = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = mail.GetDefaultFolder(6).Folders["Trial"]
df = pd.read_excel(r"C://User//Asus//Test//Test.xlsx", sheet_name = 'Sheet1')
mail = df.iloc[:,0].tolist() #this is the list of emails i.e. ends with gmail.com
processed = mail.GetDefaultFolder(6).Folders["Trial"].Folders["Done"]
add = msg.SenderEmailAddressfor msg in inbox.Items:print(msg.Subject)for attch in msg.Attachments:if any([add.endswith(m) for m in mail]) and attch.FileName[-3:] != 'png':fname = attch.FileNamedir = "C://User//Asus//Output//"tempdir = os.path.join(dir, fname)attch.SaveAsFile(tempdir)msg.Move(processed) #move the emails that completed processed to another folder

Updated Codes V2

for msg in inbox.Items:try:for attch in msg.Attachments:if msg.SenderEmailType == "SMTP" and attch.FileName[-3:] != 'png':add = msg.SenderEmailAddressprint(add, "address")fname = attch.FileNamedir = "C://User//Asus//Output//"tempdir = os.path.join(dir, fname)attch.SaveAsFile(tempdir)msg.Move(processed)elif msg.SenderEmailType == "EX" and attch.FileName[-3:] != 'png':add = msg.Sender.GetExchangeUser().PrimarySmtpAddressprint(add, "address")fname = attch.FileNamedir = "C://User//Asus//Output//"tempdir = os.path.join(dir, fname)attch.SaveAsFile(tempdir)msg.Move(processed)except Exception as e:print(e)continue
Answer

Remove msg = inbox.Items.GetFirst() and try

Example

for msg in inbox.Items:print(msg.Subject)for attch in msg.Attachments:if any(.....

Could be SenderEmailAddress so check SenderEmailType smtp or Exchange

MailItem.SenderEmailType property (Outlook)

Returns a String that represents the type of entry for the email address of the sender of the Outlook item, such as 'SMTP' for Internet address, 'EX' for a Microsoft Exchange server address, etc. Read-only.


Example

import win32com.clientmail = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = mail.GetDefaultFolder(6)for msg in inbox.Items:try:if msg.SenderEmailType == "SMTP":add = msg.SenderEmailAddressprint(add, "address")# for attch in msg.Attachments:#     if any(.....elif msg.SenderEmailType == "EX":add = msg.Sender.GetExchangeUser().PrimarySmtpAddressprint(add, "address")# for attch in msg.Attachments:#     if any(.....except Exception as e:print(e)continue

https://stackoverflow.com/a/60460848/4539709

https://en.xdnf.cn/q/119703.html

Related Q&A

IndexError: pop from empty list

I need help. I have no idea why I am getting this error. The error is in fname = 1st.pop()for i in range(num) :fname = lst.pop()lTransfer = [(os.path.join(src, fname), os.path.join(dst, fna…

Cannot import name StandardScalar from sklearn.preprocessing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

unable to solve strptime() issue even after trying all the formats

Im using the following code:data[Input_volTargetStart][1]>time.strptime(data[Dates][1], "%d %b $y")When I try to run it, I get this error:ValueError: time data 04-Jun-99 does not match for…

OSError. locateOnScreen not working in pyautogui

import pyautoguipyautogui.locateOnScreen(photo.png)Error: OSError: Failed to read photo.png because file is missing, has improper permissions, or is an unsupported or invalid format

Insert into table using For In Range and keys of the value

I have a query (sql1) that populates data, and I am trying to insert the outcome of this data (sql1) as well as other inputs into same table.Here is first query (sql1).sql1 = Select Creator_Id, Record…

Django - how to follow some object (not user) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…

Python : wildcard query in Elasticsearch

I want to query a field using wildcard in Elasticsearch but the problem is that the search string is stored in a variable and not available statically. The intended query is : body={"query": …

Extracting text between two strings

I am looking to extract the text between two patterns in my text file here is my text:Q2 2016 Apple Inc Earnings Call - FinalONI SACCONAGHI, ANALYST, BERNSTEIN: I have one, and then a follow-up, as wel…

find find with file name as variable in glob

I want to delete specific files from a list of csv files. the file name is something like this: Storm.abc.ibtracs_all.v03r10.csv. where abc is different for each file.I have a list of the abc part (nam…

Remove Special Chars from a TSV file using Regex

I have a File called "X.tsv" i want to remove special characters (including double spaces) (excluding . Single spaces Tabs / -) using regex before i export them to sub files in python I want…