Home > Net >  Saving Outlook Emails
Saving Outlook Emails

Time:05-12

I managed to get the following codes posted by GopiKrishna. It works for me, however it only saves the first email in my Outlook.

I was just wondering if a minor tweak to the code can help to save all outlook emails in inbox and/or other folders.

Credits to GopiKrishna

from win32com.client import Dispatch
import os
import re
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
print(inbox)
messages = inbox.items
message = messages.GetLast()
name = str(message.subject)
#to eliminate any special charecters in the name
name = re.sub('[^A-Za-z0-9] ', '', name) '.msg'
#to save in the current working directory
message.SaveAs(os.getcwd() '//' name)

CodePudding user response:

You will need to run for loop

Example

from win32com.client import Dispatch
import os
import re


def save_emails():
    for message in inbox.Items:
        if message.Class == 43:
            name = str(message.Subject)
            # to eliminate any special characters in the name
            name = re.sub('[^A-Za-z0-9] ', '', name)   '.msg'
            # to save in the current working directory
            message.SaveAs(os.getcwd()   '//'   name)


if __name__ == '__main__':
    outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    save_emails()
  • Related