【问题标题】:Django EmailMessage Attachments attributeDjango EmailMessage 附件属性
【发布时间】:2016-01-08 06:06:47
【问题描述】:

我尝试在一封电子邮件中发送多个附件都是 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 但这两个函数只在电子邮件中发送一个附件。

【问题讨论】:

    标签: django


    【解决方案1】:

    您应该构建一个附件列表,并在创建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 列表,因此尝试像方法一样调用它会引发错误。

    【讨论】:

    • 我真的很感谢你的帮助,很好的是仍然得到相同的结果 3 封电子邮件,每封电子邮件带有一个附件,我还必须把内容变量和 mimetype 变量放在外面,然后在外面声明把它放在附件列表中,否则会出现语法错误。
    • 我已经修复了语法错误。要使用单个电子邮件发送所有附件,您需要创建一个包含所有附件的列表,然后在循环外部发送电子邮件。
    • 太棒了!我认为主要错误是在循环内发送电子邮件非常感谢您节省了一天。
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 2011-07-21
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2011-10-05
    相关资源
    最近更新 更多