Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving email from Outlook into folder with Python

I'm trying to automate saving emails in our folders from outlook. I don't see a code for saving an email as .msg or any other type.

import win32com.client
import os
os.chdir("filepathhere")
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts;

Tokyo = "email from Tokyo"

inbox = outlook.GetDefaultFolder(6) 
subject = Tokyo
messages = inbox.Items
message = messages.GetFirst()

for msg in messages:
    if msg.subject == Tokyo:
        msgname = msg.subject
        msgname=str(msgname)
        print msgname
        message.saveasfile(msgname+".msg")

I get the error message: AttributeError: .saveasfile

like image 258
pypi34 Avatar asked Sep 08 '25 11:09

pypi34


2 Answers

The below code works:

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)
like image 150
GopiKrishna Avatar answered Sep 10 '25 05:09

GopiKrishna


SaveAsFile is a method only to be used on attachments.

For the message itself, use simply message.SaveAs().

Source: https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/mailitem-saveas-method-outlook

like image 40
GetHacked Avatar answered Sep 10 '25 05:09

GetHacked