我想重命名在Exchange服务器上收到的某些文件的附件。这可能吗?
from exchangelib import ServiceAccount, Configuration, Account, DELEGATE
from exchangelib import FileAttachment
from config import cfg
# Login
credentials = ServiceAccount(username=cfg['imap_user'],
password=cfg['imap_password'])
config = Configuration(server=cfg['imap_server'], credentials=credentials)
account = Account(primary_smtp_address=cfg['smtp_address'], config=config,
autodiscover=False, access_type=DELEGATE)
# Go through all emails, to find the example email
latest_mails = account.inbox.filter()
for msg in latest_mails:
for attachment in msg.attachments:
if attachment.name == 'numbers-test-document.pdf':
print("Rename the example attachment")
# does not work :-( - but no error either
attachment = FileAttachment(name='new-name.pdf',
content=attachment.content)
msg.attachments = [attachment]
msg.save()
print("#" * 80)
我没有收到错误消息。但它也没有重命名。代码执行(我看Rename the example attachment
),但它没有这样做。如何使用exchangelib
完成此操作?
答案 0 :(得分:0)
我必须msg.detach
和msg.attach
from exchangelib import ServiceAccount, Configuration, Account, DELEGATE
from exchangelib import FileAttachment
from config import cfg
def rename_attachment(msg, old_name, new_name):
"""
Rename an attachment `old_name` to `new_name`.
Parameters
----------
msg : Message object
old_name : str
new_name : str
Returns
-------
renames_executed : int
"""
renames_executed = 0
for attachment in msg.attachments:
if attachment.name == old_name:
renames_executed += 1
new_attachment = FileAttachment(name=new_name,
content=attachment.content)
msg.detach(attachment)
msg.attach(new_attachment)
msg.save()
return renames_executed
# Login
credentials = ServiceAccount(username=cfg['imap_user'],
password=cfg['imap_password'])
config = Configuration(server=cfg['imap_server'], credentials=credentials)
account = Account(primary_smtp_address=cfg['smtp_address'], config=config,
autodiscover=False, access_type=DELEGATE)
# Go through all emails, to find the example email
latest_mails = account.inbox.filter()
for msg in latest_mails:
rename_attachment(msg, 'numbers-test-document.pdf', 'new-name.pdf')
print("#" * 80)