我可以通过exchangelib重命名收到的电子邮件的附件吗?

时间:2017-08-01 13:06:58

标签: python exchange-server exchangelib

我想重命名在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完成此操作?

1 个答案:

答案 0 :(得分:0)

我必须msg.detachmsg.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)