Microsoft Exchange Web服务客户端(EWS)

exchangelibtmp的Python项目详细描述


Exchange Web服务客户端库

这个模块提供了一个良好的性能,良好的行为, 独立于平台的简单接口,用于与 使用Exchange Web的Microsoft Exchange 2007-2016服务器或Office365 服务(EWS)。它目前实现了自动发现和 搜索、创建、更新、删除、导出和上载 日历、邮箱、任务、联系人和通讯组列表项。

imageimageimageimageimage/p>

imagefromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)

安装

您可以从pypi安装此软件包:

pip install exchangelib

默认安装不支持kerberos。要获得其他kerberos支持,请安装 使用额外的kerberos依赖项:

pip install exchangelib[kerberos]

要安装最新的代码,请直接从github安装:

pip install git+https://github.com/ecederstrand/exchangelib.git

exchangelib使用lxml包和pykerberos来支持kerberos身份验证。 要安装这些软件,您可能需要安装一些附加的操作系统软件包。

在ubuntu上:

apt-get install libxml2-dev libxslt1-dev

# For Kerberos support, also install these:
apt-get install libkrb5-dev build-essential libssl-dev libffi-dev python-dev

在CentOS上:

# For Kerberos support, install these:
yum install gcc python-devel krb5-devel krb5-workstation python-devel

在freebsd上,pip需要一些帮助:

pkg install libxml2 libxslt
CFLAGS=-I/usr/local/include pip install lxml

# For Kerberos support, also install these:
pkg install krb5
CFLAGS=-I/usr/local/include pip install kerberos pykerberos

对于其他操作系统,请参考python包的文档 无法安装。

设置和连接

fromexchangelibimportDELEGATE,IMPERSONATION,Account,Credentials,ServiceAccount, \
    Configuration,NTLM,GSSAPI,Build,Version# Specify your credentials. Username is usually in WINDOMAIN\username format, where WINDOMAIN is# the name of the Windows Domain your username is connected to, but some servers also# accept usernames in PrimarySMTPAddress ('myusername@example.com') format (Office365 requires it).# UPN format is also supported, if your server expects that.credentials=Credentials(username='MYWINDOMAIN\\myusername',password='topsecret')# If you're running long-running jobs, you may want to enable fault-tolerance. Fault-tolerance# means that requests to the server do an exponential backoff and sleep for up to a certain# threshold before giving up, if the server is unavailable or responding with error messages.# This prevents automated scripts from overwhelming a failing or overloaded server, and hides# intermittent service outages that often happen in large Exchange installations.# If you want to enable the fault tolerance, create credentials as a service account instead:credentials=ServiceAccount(username='FOO\\bar',password='topsecret')# An Account is the account on the Exchange server that you want to connect to. This can be# the account associated with the credentials you connect with, or any other account on the# server that you have been granted access to. If, for example, you want to access a shared# folder, create an Account instance using the email address of the account that the shared # folder belongs to, and access the shared folder through this account.# 'primary_smtp_address' is the primary SMTP address assigned the account. If you enable# autodiscover, an alias address will work, too. In this case, 'Account.primary_smtp_address'# will be set to the primary SMTP address.my_account=Account(primary_smtp_address='myusername@example.com',credentials=credentials,autodiscover=True,access_type=DELEGATE)johns_account=Account(primary_smtp_address='john@example.com',credentials=credentials,autodiscover=True,access_type=DELEGATE)marys_account=Account(primary_smtp_address='mary@example.com',credentials=credentials,autodiscover=True,access_type=DELEGATE)still_marys_account=Account(primary_smtp_address='alias_for_mary@example.com',credentials=credentials,autodiscover=True,access_type=DELEGATE)# Set up a target account and do an autodiscover lookup to find the target EWS endpoint.account=Account(primary_smtp_address='john@example.com',credentials=credentials,autodiscover=True,access_type=DELEGATE)# If your credentials have been given impersonation access to the target account, set a# different 'access_type':account=Account(primary_smtp_address='john@example.com',credentials=credentials,autodiscover=True,access_type=IMPERSONATION)# If the server doesn't support autodiscover, or you want to avoid the overhead of autodiscover,# use a Configuration object to set the server location instead:config=Configuration(server='mail.example.com',credentials=credentials)account=Account(primary_smtp_address='john@example.com',config=config,autodiscover=False,access_type=DELEGATE)# 'exchangelib' will attempt to guess the server version and authentication method. If you# have a really bizarre or locked-down installation and the guessing fails, or you want to avoid# the extra network traffic, you can set the auth method and version explicitly instead:version=Version(build=Build(15,0,12,34))config=Configuration(server='example.com',credentials=credentials,version=version,auth_type=NTLM)# Kerberos authentication is supported via the 'gssapi' auth type. Enabling it is slightly awkward,# does not work with autodiscover (yet) and is likely to change in future versions.credentials=Credentials('','')config=Configuration(server='example.com',credentials=credentials,auth_type=GSSAPI)# If you're connecting to the same account very often, you can cache the autodiscover result for# later so you can skip the autodiscover lookup:ews_url=account.protocol.service_endpointews_auth_type=account.protocol.auth_typeprimary_smtp_address=account.primary_smtp_address# You can now create the Account without autodiscovering, using the cached values:config=Configuration(service_endpoint=ews_url,credentials=credentials,auth_type=ews_auth_type)account=Account(primary_smtp_address=primary_smtp_address,config=config,autodiscover=False,access_type=DELEGATE,)# Autodiscover can take a lot of time, specially the part that figures out the autodiscover # server to contact for a specific email domain. For this reason, we will create a persistent, # per-user, on-disk cache containing a map of previous, successful domain -> autodiscover server# lookups. This cache is shared between processes and is not deleted when your program exits.# A cache entry for a domain is removed automatically if autodiscovery fails for an email in that# domain. It's possible to clear the entire cache completely if you want:fromexchangelib.autodiscoverimport_autodiscover_cache_autodiscover_cache.clear()

代理和自定义TLS验证

如果需要代理支持或自定义TLS验证,可以提供 自定义"请求"传输适配器类,如中所述 http://docs.python requests.org/en/master/user/advanced/传输适配器

下面是一个使用不同自定义根证书的示例,具体取决于 要连接到的服务器:

fromurllib.parseimporturlparseimportrequests.adaptersfromexchangelib.protocolimportBaseProtocolclassRootCAAdapter(requests.adapters.HTTPAdapter):# An HTTP adapter that uses a custom root CA certificate at a hard coded locationdefcert_verify(self,conn,url,verify,cert):cert_file={'example.com':'/path/to/example.com.crt','mail.internal':'/path/to/mail.internal.crt',}[urlparse(url).hostname]super(RootCAAdapter,self).cert_verify(conn=conn,url=url,verify=cert_file,cert=cert)# Tell exchangelib to use this adapter class instead of the defaultBaseProtocol.HTTP_ADAPTER_CLS=RootCAAdapter

下面是添加代理支持的示例:

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
0

exchangelib提供忽略tls验证的示例适配器错误。自担风险使用。

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
1

文件夹

所有已知文件夹都可用作帐户的属性,例如account.rootaccount.calendaraccount.trashaccount.inboxaccount.outboxaccount.sentaccount.junkaccount.tasks帐户.联系人

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
2

日期、日期时间和时区

EWS对日期时间和时区有一些特殊要求。你需要 要使用特殊的类 处理日期时。

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
3

创建、更新、删除、发送和移动

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
4

批量操作

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
5

搜索

搜索是根据django queryset api建模的,并且 支持API。就像在Django,Queryset很懒 在迭代queryset之前获取任何内容。QuerySets支持 链接,以便您可以在多个步骤中构建最终查询,并且 可以对多个子搜索重复使用基本查询集。查询集 返回一个迭代器,当QuerySet完全 第一次迭代。

下面是一些使用api的示例:

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
6

分页

寻呼EWS服务(例如finditem和)的默认页面大小为100。你可以 如果需要,请全局更改此值:

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
7

如果您使用的是非常小或非常大的项目,这可能不合理 价值。例如,如果要检索和保存带有大型附件的电子邮件, 您可以根据每个查询集更改此值:

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
8

最后,在account类中定义的bulk方法有一个可选的块大小 参数,可用于在获取、创建、更新时设置非默认页大小。 或删除项目。

fromexchangelibimportCredentials,Accountcredentials=Credentials('john@example.com','topsecret')account=Account('john@example.com',credentials=credentials,autodiscover=True)foriteminaccount.inbox.all().order_by('-datetime_received')[:100]:print(item.subject,item.sender,item.datetime_received)
9

会议

日历项类允许您发送会议请求 您发起或取消以前已开始的会议。它 也可以处理接收到的会议请求消息。 您可以使用acceptitem回复这些消息, tentivelyacceptitemdeclineitem类。如果你收到 取消您的会议(classmeeting cancellation) 已经接受,然后您也可以通过删除条目来处理这些 从日历中。

pip install exchangelib
0

搜索联系人

支持使用相同的 语法为文件夹。只需使用.people()

开始查询
pip install exchangelib
1

扩展属性

扩展属性使附加自定义键值对成为可能 到Exchange服务器上的项目和文件夹。有多个在线 描述如何使用扩展属性并列出许多 现有Exchange客户端用来存储 公共和自定义属性。以下内容并不全面 对可能性的描述,但我们确实打算支持 EWS提供的可能性。

pip install exchangelib
2

附件

pip install exchangelib
3

周期性日历项

对创建定期日历项提供完全的读写支持。 您可以创建每日、每周、每月和每年的重复(后者 两个相对和绝对版本)。

下面是在星期一和星期三创建7个事件的示例 每三周,从2017年9月1日开始:

pip install exchangelib
4

消息时间戳字段

每个消息项都有四个时间戳字段:

  • 创建日期时间
  • 发送日期时间
  • 已收到日期时间
  • 上次修改时间

这些字段的值由Exchange服务器设置,而不是 可通过EWS修改。所有值都可以识别时区ewsdatetime 实例S.P/P>

发送的日期时间值可能早于创建的日期时间值。

设施不足

您可以使用帐户获取和设置oof消息。oof\u设置 属性:

pip install exchangelib
5

导出并上载

Exchange支持使用特殊的 导出和上载服务。它们在帐户上可用型号:

pip install exchangelib
6

非帐户方法

pip install exchangelib
7

EWS支持获取特定 时间框架。服务器为每个包含忙/闲的帐户返回一个对象 信息,包括用户日历中的日历事件列表,以及 用户的工作时间和时区。

pip install exchangelib
8

日历事件和工作时间返回为原始日期时间。皈依 对于支持时区的日期时间,如果用户没有 已知位于同一时区。

pip install exchangelib
9

故障排除

如果你在使用这个库时遇到问题,首先要尝试的是 启用调试日志记录。这将输出大量的信息 关于正在发生的事情,最值得注意的是 越过电线。这可以非常方便地查看哪些字段是 发送和接收。

pip install exchangelib[kerberos]
0

大多数类定义都有一个docstring,其中至少包含指向 对应XML元素的MSDN页。

pip install exchangelib[kerberos]
1

注释

几乎所有项字段都受支持。剩下的被追踪 https://github.com/ecederstrand/exchangelib/issues/203

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
如何下载多个。java中的PDF文件   linux Java打开文件,形成实际用户主页~/   java如何在时间线内维护TableView选择?   java Hibernate注释@Where vs@WhereJoinTable   Java读/写访问异常FileNotFoundException(访问被拒绝)   继承在Java中是否可以扩展最后一个类?   Android HttpClient使用java使应用程序崩溃。lang.OutOfMemoryError:pthread_create   java为什么即使我在proguardproject中添加了jar文件,也会出现这种错误。txt?   如果添加JButton,swing Java FocusListener和KeyListener将无法工作   java使用solrj检索json格式的SolrDocument   使用Microsoft Visual Studio代码进行Java编程   java NoClassDefFoundError:org/apache/log4j/Logger   哈希集中包含相等对象的java   java中的参数化构造函数是否需要有一个主体?   java类似于NetBeans不必要的代码检测器   Java实践问题   java Blackberry“[projectname].调试文件丢失”和“I/O错误:找不到程序”jar