The below code works on my W10 laptop, but not on my w10 or w7 virtual desktop (VMWare).
It reads emails and save attachments from a specific sender to a shared network drive, and moves the email to a sub folder.
I guess I need to change the line:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
any pointers much appreciated.
import win32com.client
import re
path='//shared_drive/StatementFiles/'
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
donebox = outlook.GetDefaultFolder(6).folders("Bank").folders("Statements")
messages = inbox.Items# get the first email
message = messages.GetLast()
sender_name = 'sender@email.com'
i = 1
while i < 100:
message = messages.GetLast()
try:
current_sender = str(message.Sender).lower()
current_subject = str(message.Subject)
messagedate = message.senton
if re.search(sender_name, current_sender) != None:
print(current_subject) # verify the subject
print(current_sender) # verify the sender
attachments = message.Attachments
attachment = attachments.Item(1)
attachment_name = str(attachment).lower()
attachment.SaveASFile(path + attachment_name)
att_path=path + attachment_name
message.UnRead = False
message.Move(donebox)
current_sender = str(message.Sender).lower()
current_subject = str(message.Subject)
print(f'Email moved.')
message = messages.GetNext()
except:
message = messages.GetNext()
i += 1
I don't have Python installed on eiter of the virtual desktops, still waiting for it to be packaged, and I don't have the permissions to install, so on the virtual desktops I am running an exe file created with PyInstaller - again, this exe works correctly on my laptop. Running this exe via cmd prompts returns no message or error.
Oddly running this on a virtual desktop you need to reverse the order, so instead of going for GetLast, using GetFirst resolved this. Did hit another snag where Outlook brings up a message to allow an programme to emails, of either 1, 2, 5 or 10 minutes. I couldn't find a way to deactivate this on our VMWare, so have decided to switch to VBA, which is now doing what I need. Frustrating, but at least it's a solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.