2

I'm working with exchangelib and python3 to manage an Exchange mailbox, so far my code works ok, but I wanted to check how many attachments an email has before to go forward.

This is what I have so far:

def send_email(account, subject, body, recipients, attachments=None):
    to_recipients = []
    for recipient in recipients:
        to_recipients.append(Mailbox(email_address=recipient))
    # Create message
    m = Message(account=account,
                folder=account.sent,
                subject=subject,
                body=body,
                to_recipients=to_recipients)

    b = attachments.count
    log.info(b)
    m.attach(attachments)
    m.send_and_save()

I'm calling this function to create a new email from a previous one I've received with attachments. When the email has a just one attachment it works fine, however when the received email has more than one attachment it fail. That is why I wanted to check how many attachments the received email has before to proceed.

I found out this attribute for attachments object but the result I got is this:

<built-in method count of list object at 0x10a23be10>

So, how could I check if the attachments object, which is a type FileAttachment,has more than one attachment? Even better, how could I attach more than one attachment to my new email? For the last question I have this code, which does not work:

for attachment_name, attachment_content in attachments or []:
        log.info('loop attachments')
        file = FileAttachment(name=attachment_name, content=attachment_content)
        m.attach(file)

This is the error I'm receiving:

for attachment_name, attachment_content in attachments or []:
TypeError: cannot unpack non-iterable FileAttachment object
Sallyerik
  • 489
  • 2
  • 11
  • 24

1 Answers1

0

There are multiple misconceptions here.

First, you need to check first which type your attachments argument is. Judging by the output, you are passing a list (the built-in list type). Later on, you are printing attachments.count which is actually the list.count() method (see https://docs.python.org/3.8/tutorial/datastructures.html), which does not make sense to print. If you want to get the size of the attachments argument, use len(attachments), since it's just a list.

A single FileAttachment is one attachment, not a list of attachments. Instead, I assume that your attatchments argument is a list of FileAttachment objects.

Regarding the last TypeError, you are iterating over a list of FileAttachment objects, but then treating each object as if it were a tuple by trying to unpack the object. That won't work. If you want to access the name and content attributes of each FileAttachment, do this instead:

for a in attachments:
    print(a.name, a.content)
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63