Используя win32com и/или active_directory, как я могу получить доступ к папке электронной почты по имени?

В python с Outlook 2007, используя win32com и/или active_directory, как я могу получить ссылку на подпапку, чтобы я мог переместить MailItem в эту подпапку?

I have an inbox structure like:

    Inbox
      |
      +-- test
      |
      `-- todo

Я могу получить доступ к папке «Входящие», например:

import win32com.client
import active_directory
session = win32com.client.gencache.EnsureDispatch("MAPI.session")
win32com.client.gencache.EnsureDispatch("Outlook.Application")
outlook = win32com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace('MAPI')
inbox =  mapi.GetDefaultFolder(win32com.client.constants.olFolderInbox)
print '\n'.join(dir(inbox))

Но когда я пытаюсь получить подкаталог test согласно примеру Microsoft, объект inbox не имеет интерфейса Folders или какого-либо способа получить подкаталог.

Как я могу получить объект Folder, который указывает на подкаталог test?


person Ross Rogers    schedule 11.01.2010    source источник


Ответы (4)


Я понимаю, что это старый вопрос, но недавно я использовал пакет win32com и нашел документацию, по меньшей мере, сложной... Я надеюсь, что кто-то когда-нибудь сможет спасти суматоху, с которой я столкнулся, пытаясь обернуть голову вокруг MSDN. объяснение

Вот и пример скрипта Python для обхода папок Outlook, доступа к электронной почте, где мне угодно.

Отказ от ответственности Я изменил код и удалил некоторые конфиденциальные данные, поэтому, если вы пытаетесь скопировать и вставить его и запустить, удачи.

import win32com
import win32com.client
import string
import os
# the findFolder function takes the folder you're looking for as folderName,
# and tries to find it with the MAPIFolder object searchIn

def findFolder(folderName,searchIn):
try:
    lowerAccount = searchIn.Folders
    for x in lowerAccount:
        if x.Name == folderName:
            print 'found it %s'%x.Name
            objective = x
            return objective
    return None
except Exception as error:
    print "Looks like we had an issue accessing the searchIn object"
    print (error)
    return None

def main():

outlook=win32com.client.Dispatch("Outlook.Application")

ons = outlook.GetNamespace("MAPI")

#this is the initial object you're accessing, IE if you want to access
#the account the Inbox belongs too
one = '<your account name here>@<your domain>.com'

#Retrieves a MAPIFolder object for your account 
#Object functions and properties defined by MSDN at 
#https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mapifolder_members(v=office.14).aspx
Folder1 = findFolder(one,ons)

#Now pass you're MAPIFolder object to the same function along with the folder you're searching for
Folder2 = findFolder('Inbox',Folder1)

#Rinse and repeat until you have an object for the folder you're interested in
Folder3 = findFolder(<your inbox subfolder>,Folder2)

#This call returns a list of mailItem objects refering to all of the mailitems(messages) in the specified MAPIFolder
messages = Folder3.Items

#Iterate through the messages contained within our subfolder
for xx in messages:
    try:
        #Treat xx as a singular object, you can print the body, sender, cc's and pretty much every aspect of an e-mail
       #In my case I was writing the body to .txt files to parse...
        print xx.Subject,xx.Sender,xx.Body
       #Using move you can move e-mails around programatically, make sure to pass it a 
        #MAPIFolder object as the destination, use findFolder() to get the object
        xx.Move(Folder3)


    except Exception as err:
        print "Error accessing mailItem"
        print err       


if __name__ == "__main__":
main()

PS Надеюсь, это не принесет больше вреда, чем пользы.

person Tony Tyrrell    schedule 06.05.2015
comment
Спасибо Тони. Ага. Я обнаружил, что работа с этим также была болезненной. - person Ross Rogers; 07.05.2015

Что-то, что действительно сработало для меня, было перебором имен папок. (Когда я разместил этот вопрос, я не мог понять имена папок).

import win32com.client
import active_directory
session = win32com.client.gencache.EnsureDispatch("MAPI.session")
win32com.client.gencache.EnsureDispatch("Outlook.Application")
outlook = win32com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace('MAPI')
inbox =  mapi.GetDefaultFolder(win32com.client.constants.olFolderInbox)

fldr_iterator = inbox.Folders   
desired_folder = None
while 1:
    f = fldr_iterator.GetNext()
    if not f: break
    if f.Name == 'test':
        print 'found "test" dir'
        desired_folder = f
        break

print desired_folder.Name
person Ross Rogers    schedule 11.01.2010

Это работает для меня, чтобы переместить элемент почты в подкаталог "test" (упрощенный путем избавления от материала gencache):

import win32com.client

olFolderInbox = 6
olMailItem = 0

outlook = win32com.client.Dispatch("Outlook.Application")
mapi = outlook.GetNamespace('MAPI')
inbox =  mapi.GetDefaultFolder(olFolderInbox)

item = outlook.CreateItem(olMailItem)
item.Subject = "test"

test_folder = inbox.Folders("test")
item.Move(test_folder)
person Ryan Ginstrom    schedule 11.01.2010
comment
Этот звонок не работает для меня inbox.Folders('test'). Однако я обнаружил, что могу перебрать inbox.Folders и протестировать a_folder.Name. - person Ross Rogers; 11.01.2010
comment
Кроме того, вы можете найти все эти константы Outlook в win32com -- win32com.client.constants.olFolderInbox - person Ross Rogers; 11.01.2010

Таким образом, приведенный ниже код захватит «Последний» элемент в папке SOURCE, а затем переместит его в папку DEST. Извините, код немного тупой, я удалил все дополнительные функции, такие как чтение и сохранение почты.

import win32com.client

inbox = win32com.client.gencache.EnsureDispatch("Outlook.Application").GetNamespace("MAPI")


source = inbox.GetDefaultFolder(6).Folders["FOLDER_NAME_SOURCE"]
dest = inbox.GetDefaultFolder(6).Folders["FOLDER_NAME_DEST"]


def moveMail(message):
    print("moving mail to done folder")
    message.Move(dest)
    return print("MOVED")


def getMail():
    message = source.Items.GetLast()
    moveMail(message)


getMail()
person Dayantat    schedule 24.09.2018