attach file like object to email python 3

前端 未结 1 1598
南旧
南旧 2021-01-18 02:57

I have found a lot of examples on the net of how to attach local files to an email. What I want to do is attach a file like object to an email. Why you ask? so I don\'t have

相关标签:
1条回答
  • 2021-01-18 03:14

    Turns out I should have read

    E-Mail Examples from Python Docs

    more closely. Im pretty sure its because I was using only 1 MIME type object to build my email but trying to add multiple MIME objects. Basically to get it to work I used the below code. Happy days!

    def email_sup_teams(team_name, contact_list, file_attachemnt):
        message_list = []
        for jobs in file_attachemnt:
            for k, v in jobs.items():
                message_list.append(v + ',')
        attachment_text = "\n".join(message_list)
        print(type(attachment_text))
        # Create the container (outer) email message.
        msg = MIMEMultipart()
        #msg = MIMEText(' Failed jobs list. Please see attachment')
        msg['Subject'] = 'Not run Jobs for ' + team_name
        msg['From'] = 'a@b.com'
        msg['To'] = 'c@d.com'
        msg.preamble = 'Failed jobs list. Please see attachment'
        f = io.StringIO(attachment_text)
        attachment = MIMEText(f.getvalue())
        attachment.add_header('Content-Disposition', 'attachment', filename='jobs_not_run.xls')           
        msg.attach(attachment)
    
        s = smtplib.SMTP('smlsmtp')
        s.sendmail(msg['From'], msg['To'], msg.as_string())
        s.quit()
        print('\n' + team_name + ' Email Sent')
    
    0 讨论(0)
提交回复
热议问题