与操作文件夹相同,获取联系人只需使用.people()方法:
# 移动到联系人文件夹并开始搜索
from exchangelib import Account, DistributionList
from exchangelib.indexed_properties import EmailAddress
a = Account(...)
folder = a.root / 'AllContacts'
for p in folder.people():
print(p)
for p in folder.people().only('display_name').filter(display_name='john').order_by('display_name'):
print(p)
# 从GAL文件夹获取指定联系人
gal = a.contacts / 'GAL Contacts'
contact = gal.get(email_addresses=EmailAddress(email='lucas@example.com'))
# 所有使用Gmail的联系人
gmail_contacts = list(gal.filter(email_addresses__contains=EmailAddress(email='gmail.com')))
# 所有Gmail邮件地址
gmail_addresses = [e.email for c in gal.filter(email_addresses__contains=EmailAddress(email='gmail.com'))
for e in c.email_addresses]
# 所有邮件地址
all_addresses = [e.email for c in gal.all()
for e in c.email_addresses if not isinstance(c, DistributionList)]
联系人有照片和备注字段,但它们不能使用。您可以使用如下方式来添加联系人照片和备注:
from exchangelib import Account, FileAttachment
a = Account(...)
contact = a.contacts.get(given_name='John')
contact.body = 'This is a note'
contact.save(update_fields=['body'])
att = FileAttachment(
name='ContactPicture.jpg',
content_type='image/png',
is_inline=False,
is_contact_photo=True,
content=open('john_profile_picture.png', 'rb').read(),
)
contact.attach(att)