在django中通过smtplib发送带有多个附件的电子邮件时,只能打开最后一个附件

wbrvyc0a  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(153)

我正在创建一个Django应用程序,它可以将上传的文件发送给其他用户,但只有邮件附件中的最后一个文件是可读的,其余的都被损坏了,我不知道为什么。
下面是我用来创建电子邮件和添加附件的代码。当它只有一个文件时,一切都很完美。

attachments         = request.FILES
            msg                 = MIMEMultipart()
            msg['Subject']      = subject
            msg['From']         = EMAIL_ADDRESS
            msg['To']           = ', '.join(recipients)

            msg.attach(MIMEText(body,"html"))
            
            if len(attachments.getlist('attachment')) != 0:
                for attachment in attachments.getlist('attachment'):

                    attach_file     = attachment.file
                    payload         = MIMEBase('application', attachment.content_type)
                    payload.set_payload(attach_file.read())
                    encoders.encode_base64(payload)
                    payload.add_header('content-disposition', 'attachment',filename=attachment.name)
                    msg.attach(payload)

            smtp_server         = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            
            smtp_server.login(EMAIL_ADDRESS, PASSWORD)
            smtp_server.sendmail(EMAIL_ADDRESS, recipients, msg.as_string())
            smtp_server.quit()

我也尝试了django类EmailMessage,但结果完全相同。

tct7dpnv

tct7dpnv1#

对我来说,这很有效:

from email.mime.application import MIMEApplication

if len(attachments.getlist('attachment')) != 0:
   for attachment in attachments.getlist('attachment'):
       at = MIMEApplication(open(attachment, 'rb').read())
       at.add_header('Content-Disposition', 'attachment', 
                      filename=attachment.name)
       msg.attach(at)

相关问题