add excel file attachment when sending python email

前端 未结 4 578
离开以前
离开以前 2020-11-28 07:25

How do i add a document attachment when sending an email with python ? i get the email to send (please ignore: i am looping the email to send every 5 seconds, only for testi

4条回答
  •  温柔的废话
    2020-11-28 08:23

    Here is just a slight tweak on SoccerPlayer's post above that got me 99% of the way there. I found a snippet Here that got me the rest of the way. No credit is due to me. Just posting in case it helps the next person.

    file = 'File.xlsx'
    username=''
    password=''
    send_from = ''
    send_to = 'recipient1 , recipient2'
    Cc = 'recipient'
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Cc'] = Cc
    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = ''
    server = smtplib.SMTP('smtp.gmail.com')
    port = '587'
    fp = open(file, 'rb')
    part = MIMEBase('application','vnd.ms-excel')
    part.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
    msg.attach(part)
    smtp = smtplib.SMTP('smtp.gmail.com')
    smtp.ehlo()
    smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
    smtp.quit()
    

提交回复
热议问题