首页 文章

Django EmailMessage附件属性

提问于
浏览
0

我尝试发送一封电子邮件多个附件都是PDF格式,这是我的代码

for pdf_files in glob.glob(path+str(customer)+'*.*'):

                    get_filename = os.path.basename(pdf_files)


                    list_files = [get_filename]




                    attachment = open(path+get_filename, 'rb')

                    email = EmailMessage('Report for'+' '+customer,
                        'Report Date'+' '+cust+', '+cust, to=['asd@asd.com'])

                    email.attachments(filename=list_files, content=attachment.read(), mimetype='application/pdf')

                    email.send()

以下是Django文档中有关附件属性的内容 .

附件:要放在邮件上的附件列表 . 这些可以是email.MIMEBase.MIMEBase实例,或(filename,content,mimetype)三元组 .

当我尝试使用附件运行此代码时,我总是会收到此错误

TypeError: 'list' object is not callable

也许我误解了,但是我传递了一份文件列表,比如文档说的请一些人有一个例子 . 我到处看,所有人都使用attach和attach_files,但这两个函数只在电子邮件中发送一个附件 .

1 回答

  • 0

    您应该构建一个附件列表,并在创建 EmailMessage 时使用它 . 如果要通过一封电子邮件发送所有附件,则需要先创建所有附件的列表,然后在循环外发送电子邮件 .

    我已经稍微简化了代码,因此你必须对其进行调整,但希望这会让你开始 .

    # Loop through the list of filenames and create a list
    # of attachments, using the (filename, content, mimetype) 
    # syntax.
    
    attachments = []  # start with an empty list
    for filename in filenames:
        # create the attachment triple for this filename
        content = open(filename, 'rb').read()
        attachment = (filename, content, 'application/pdf')
        # add the attachment to the list
        attachments.append(attachment)
    
    # Send the email with all attachments
    email = EmailMessage('Hello', 'Body goes here', 'from@example.com',
            ['to1@example.com', 'to2@example.com'], attachments=attachments)
    email.send()
    

    email.attachments 属性是 email 实例的实际附件列表 . 它是一个Python列表,因此尝试像方法一样调用它会引发错误 .

相关问题