通过 Python 读取 Outlook 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21477599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:56:41  来源:igfitidea点击:

Read Outlook Events via Python

pythonpython-2.7outlook-2010win32com

提问by Norfeldt

Outlook has some things to desire - like showing multiple month view

Outlook 有一些需要的东西 - 比如显示多月视图

So I decided to give it a try by pulling out the event data via python (and then figure a way to display it nicely). Google is giving me pore results, but stackoverflow has been very helpful previously in regards to using win32com and outlook.

所以我决定通过python提取事件数据来尝试一下(然后想办法很好地显示它)。谷歌给了我毛孔结果,但 stackoverflow 以前在使用 win32com 和 Outlook 方面非常有帮助。

My goals are the following

我的目标如下

  • read a shared calendar
  • read the events information like start, end, subject, creater etc
  • 阅读共享日历
  • 读取事件信息,如开始、结束、主题、创建者等

I haven't got far, but this is what I got together (with inspiration from this site)

我还没有走多远,但这就是我聚在一起的(灵感来自这个网站

import win32com.client, datetime
from dateutil.relativedelta import relativedelta

Outlook = win32com.client.Dispatch("Outlook.Application")
ns = Outlook.GetNamespace("MAPI")

appointments = namespace.GetDefaultFolder(9).Items 
# TODO: Need to figure out howto get the shared calendar instead Default [9] 
# (I have placed the shared folder into a separate folder - don't know if it matters)
# I would just like the user to select which calendar to execute on
appointments.Sort("[Start]")
appointments.IncludeRecurrences = "True"
begin = date.today().strftime("%m%d%Y")
end = (date.today() + relativedelta( months = 3 )).strftime("%m%d%Y")
appointments = appointments.Restrict("[Start] >= '" +begin+ "' AND [END] >= '" +end+ "'")

From here I need help with looping through the events and read them. Any help is highly appreciated.

从这里我需要帮助循环遍历事件并阅读它们。任何帮助都受到高度赞赏。

回答by Andreas Fester

From here I need help with looping through the events and read them.

从这里我需要帮助循环遍历事件并阅读它们。

Basically, all you have to do is to follow the COM API documentation from Microsoft. For example, the Restrict()method returns AppointmentItemobjects which are documented at AppointmentItem Objectfor Outlook 2010. So, starting with a folder, you can get and list the appointments as follows:

基本上,您所要做的就是遵循 Microsoft 的 COM API 文档。例如,该Restrict()方法返回AppointmentItem在Outlook 2010 的AppointmentItem 对象中记录的对象。因此,从文件夹开始,您可以获取并列出约会,如下所示:

# Get the AppointmentItem objects
# http://msdn.microsoft.com/en-us/library/office/aa210899(v=office.11).aspx
appointments = someFolder.Items

# Restrict to items in the next 30 days (using Python 3.3 - might be slightly different for 2.7)
begin = datetime.date.today()
end = begin + datetime.timedelta(days = 30);
restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") + "' AND [End] <= '" +end.strftime("%m/%d/%Y") + "'"
restrictedItems = appointments.Restrict(restriction)

# Iterate through restricted AppointmentItems and print them
for appointmentItem in restrictedItems:
    print("{0} Start: {1}, End: {2}, Organizer: {3}".format(
          appointmentItem.Subject, appointmentItem.Start, 
          appointmentItem.End, appointmentItem.Organizer))

Note that I had to use a slightly different time format for the restriction expression ("%m/%d/%Y"instead of "%m%d%Y"). The proper solution would be to use Outlook's Formatfunction as documented at http://msdn.microsoft.com/en-us/library/office/ff869597(v=office.14).aspx, section Date. Note also that I was using Python 3.3, so you might have to use different functions to create the dates. In any case, for testing purposes, you can use a hard coded expression like "[Start] >= '02/03/2014' AND [End] <= '03/05/2014'"

请注意,我必须对限制表达式("%m/%d/%Y"而不是"%m%d%Y")使用稍微不同的时间格式。正确的解决方案是使用http://msdn.microsoft.com/en-us/library/office/ff869597(v=office.14).aspx部分Date 中Format记录的Outlook功能。另请注意,我使用的是 Python 3.3,因此您可能必须使用不同的函数来创建日期。在任何情况下,出于测试目的,您都可以使用硬编码表达式,例如"[Start] >= '02/03/2014' AND [End] <= '03/05/2014'"

To get a shared calendar, the following code should work - This is the usual sequence found in the API documentation, however I was not able to actually get it working, but this could be due to a different backend server (not using an Exchange server):

要获取共享日历,以下代码应该可以工作 - 这是 API 文档中的常用顺序,但是我无法实际使其正常工作,但这可能是由于不同的后端服务器(未使用 Exchange 服务器) ):

recipient = namespace.createRecipient("User Name")
resolved = recipient.Resolve()
sharedCalendar = namespace.GetSharedDefaultFolder(recipient, 9)

To show all available folders as a tree, you can use something like

要将所有可用文件夹显示为树,您可以使用类似

def folderTree(folders, indent = 0):
    prefix = ' ' * (indent*2)
    i = 0
    for folder in folders:
        print("{0}{1}. {2} ({3})".format(prefix, i, folder.Name, folder.DefaultItemType))
        folderTree(folder.Folders, indent + 1)
        i = i + 1

...
folderTree(namespace.Folders)

To look up a folder by its path (e.g. to find the calendar folder "[email protected]" below the "Internet Calendars" folder), you can use something like

要按路径查找文件夹(例如,在“Internet 日历”文件夹下查找日历文件夹“[email protected]”),您可以使用类似

def findFolder(folders, searchPath, level = 0):
    for folder in folders:
        if folder.Name == searchPath[level]:
            if level < len(searchPath)-1:
                # Search sub folder
                folder = findFolder(folder.folders, searchPath, level+1)
            return folder
    return None

...
sharedCalendar = findFolder(namespace.Folders, ["Internet Calendars", "[email protected]"])

See also:

也可以看看: