我正在使用exchangelib和python3管理Exchange邮箱,到目前为止,我的代码工作正常,但我想检查一封电子邮件之前有多少附件
这就是我到目前为止所做的:
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()
我调用此函数是为了从以前收到的带有附件的电子邮件中创建一封新电子邮件。当电子邮件只有一个附件时,它可以正常工作,但是当收到的电子邮件有多个附件时,它会失败。这就是为什么我想检查收到的电子邮件在继续之前有多少附件
我为attachments
对象找到了这个属性,但得到的结果是:
<built-in method count of list object at 0x10a23be10>
那么,我如何检查类型为FileAttachment
的attachments
对象是否有多个附件呢?更妙的是,我怎样才能在我的新电子邮件中附加多个附件?
对于最后一个问题,我有这个代码,它不起作用:
for attachment_name, attachment_content in attachments or []:
log.info('loop attachments')
file = FileAttachment(name=attachment_name, content=attachment_content)
m.attach(file)
这是我收到的错误:
for attachment_name, attachment_content in attachments or []:
TypeError: cannot unpack non-iterable FileAttachment object
这里有很多误解
首先,您需要首先检查
attachments
参数的类型。根据输出判断,您正在传递一个列表(内置的list
类型)。稍后,您将打印attachments.count
,这实际上是list.count()
方法(请参见https://docs.python.org/3.8/tutorial/datastructures.html),这对打印没有意义。如果要获取attachments
参数的大小,请使用len(attachments)
,因为它只是一个列表单个
FileAttachment
是一个附件,而不是附件列表。相反,我假设attatchments
参数是FileAttachment
对象的列表关于最后一个
TypeError
,您正在迭代一个FileAttachment
对象列表,但是通过尝试解压对象,将每个对象视为元组。那不行。如果要访问每个FileAttachment
的name
和content
属性,请执行以下操作:相关问题 更多 >
编程相关推荐