How to send email attachments?

前端 未结 13 927
梦谈多话
梦谈多话 2020-11-22 01:14

I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please e

13条回答
  •  孤街浪徒
    2020-11-22 01:44

    This is the code I ended up using:

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    
    
    SUBJECT = "Email Data"
    
    msg = MIMEMultipart()
    msg['Subject'] = SUBJECT 
    msg['From'] = self.EMAIL_FROM
    msg['To'] = ', '.join(self.EMAIL_TO)
    
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("text.txt", "rb").read())
    Encoders.encode_base64(part)
        
    part.add_header('Content-Disposition', 'attachment; filename="text.txt"')
    
    msg.attach(part)
    
    server = smtplib.SMTP(self.EMAIL_SERVER)
    server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
    

    Code is much the same as Oli's post.

    Code based from Binary file email attachment problem post.

提交回复
热议问题