Binary file email attachment problem

后端 未结 3 2032
别跟我提以往
别跟我提以往 2021-01-05 06:11

Using Python 3.1.2 I am having a problem sending binary attachment files (jpeg, pdf, etc.) - MIMEText attachments work fine. The code in question is as follows...



        
3条回答
  •  生来不讨喜
    2021-01-05 06:15

    solution from this SO answer

    from base64 import encodebytes
    for file in self.attachments:
        fp = open(file, 'rb')
        part = MIMEBase('application', "octet-stream")
        part.set_payload(encodebytes(fp.read()).decode())
        fp.close()
        part.add_header('Content-Transfer-Encoding', 'base64')
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
        msg.attach(part)   # msg is an instance of MIMEMultipart()
    
    server = smtplib.SMTP(host, port)
    server.login(username, password)
    server.sendmail(from_addr, all_recipients, msg.as_string())
    

提交回复
热议问题