12. Exchangelib3.2官方文档 —— 附件

# 可以创建、删除和获取任何项目类型的附件
# FileAttachment类'content'属性包含文件二进制内容
# ItemAttachment类'item'属性为邮件的任意对象实例,该实例可以是Message, CalendarItem, Task等类型
import os.path
from exchangelib import Account, FileAttachment, ItemAttachment, Message, CalendarItem, HTMLBody

a = Account
for item in a.inbox.all():
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            local_path = os.path.join('/tmp', attachment.name)
            with open(local_path, 'wb') as f:
                f.write(attachment.content)
            print('Saved attachment to', local_path)
        elif isinstance(attachment, ItemAttachment):
            if isinstance(attachment.item, Message):
                print(attachment.item.subject, attachment.item.body)

# 还支持附件的流式下载。这减少了内存消耗,避免文件的全部内容存储在内存中:
for item in a.inbox.all():
    for attachment in item.attachments:
        if isinstance(attachment, FileAttachment):
            local_path = os.path.join('/tmp', attachment.name)
            with open(local_path, 'wb') as f, attachment.fp as fp:
                buffer = fp.read(1024)
                while buffer:
                    f.write(buffer)
                    buffer = fp.read(1024)
            print('Saved attachment to', local_path)

# 创建带附件的项
item = Message(...)
binary_file_content = 'Hello from unicode æøå'.encode('utf-8')  # Or read from file, BytesIO etc.
my_file = FileAttachment(name='my_file.txt', content=binary_file_content)
item.attach(my_file)
my_calendar_item = CalendarItem(...)
my_appointment = ItemAttachment(name='my_appointment', item=my_calendar_item)
item.attach(my_appointment)
item.save()

# 附件附加到现有项
my_other_file = FileAttachment(name='my_other_file.txt', content=binary_file_content)
item.attach(my_other_file)

# 删除附件
item.detach(my_file)

# 如果要在正文中嵌入图像,可以将图像链接到HTML中
message = Message(...)
logo_filename = 'logo.png'
with open(logo_filename, 'rb') as f:
    my_logo = FileAttachment(name=logo_filename, content=f.read(), is_inline=True, content_id=logo_filename)
message.attach(my_logo)
message.body = HTMLBody('<html><body>Hello logo: <img src="cid:%s"></body></html>' % logo_filename)

# 无法更新附件。在这种情况下,必须先分离附件,更新相关字段,然后加更新后的附件。

# 请注意,添加和删除已在Exchange中创建的实例(具有item_id的项目)的附件将更新changekey。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值