Attach file as object to python 3 email

I found many examples on the web how to attach local files to email. What I want to do is attach an object-like file to an email address. Why do you ask? so I donโ€™t need to clean up the files. Below is my code and my error. After long searches, I still couldnโ€™t get it to work, any help would be greatly appreciated :)

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)) 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 ' f = io.StringIO(attachment_text) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename='test_attach') msg.attach(attachment) s = smtplib.SMTP('smlsmtp') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.quit() print('\n' + team_name + ' Email Sent') 

Error:

 <class 'str'> Traceback (most recent call last): File "queue_cleaner_main.py", line 85, in <module> sys.exit(main()) File "queue_cleaner_main.py", line 82, in main queue_cleaner_functions.email_sup_teams(t, team_members_emails, attachment_file_of_jobs) File "D:\oppssup\old_job\queue_cleaner_functions.py", line 179, in email_sup_teams msg.attach(attachment) File "C:\Python34\lib\email\mime\nonmultipart.py", line 22, in attach 'Cannot attach additional subparts to non-multipart/*') email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/* 
+5
source share
1 answer

It turns out I had to read

https://docs.python.org/3/library/email-examples.html

more closely. I'm sure this is because I used only one MIME object to create my email, but I am trying to add multiple MIME objects. Basically, to make it work, I used the code below. 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') 
+5
source

All Articles