How do I send attachments using SMTP?

后端 未结 6 903
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 01:55

I want to write a program that sends email using Python\'s smtplib. I searched through the document and the RFCs, but couldn\'t find anything related to attachments. Thus,

6条回答
  •  执念已碎
    2020-12-01 02:04

    Here's an example I snipped out of a work application we did. It creates an HTML email with an Excel attachment.

      import smtplib,email,email.encoders,email.mime.text,email.mime.base
    
      smtpserver = 'localhost'
      to = ['email@somewhere.com']
      fromAddr = 'automated@hi.com'
      subject = "my subject"
    
      # create html email
      html = ''
      html +='

    ...

    ' html += "" emailMsg = email.MIMEMultipart.MIMEMultipart('alternative') emailMsg['Subject'] = subject emailMsg['From'] = fromAddr emailMsg['To'] = ', '.join(to) emailMsg['Cc'] = ", ".join(cc) emailMsg.attach(email.mime.text.MIMEText(html,'html')) # now attach the file fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel') fileMsg.set_payload(file('exelFile.xls').read()) email.encoders.encode_base64(fileMsg) fileMsg.add_header('Content-Disposition','attachment;filename=anExcelFile.xls') emailMsg.attach(fileMsg) # send email server = smtplib.SMTP(smtpserver) server.sendmail(fromAddr,to,emailMsg.as_string()) server.quit()

提交回复
热议问题