1

I want to rename the attachments of some files I receive on an Exchange server. Is this possible?

What I've tried

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)

I don't get an error message. But it doesn't rename either. The code executes (I see Rename the example attachment), but it doesn't do so. How can this be done with exchangelib?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

0

I have to take msg.detach and msg.attach

Complete working script

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)
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958