将对象之类的文件附加到电子邮件python 3 [英] attach file like object to email python 3
问题描述
我在网上找到了很多关于如何将本地文件附加到电子邮件的示例.我想要做的是将像对象这样的文件附加到电子邮件中.你为什么问?所以我不必处理清理文件.下面是我的代码和我的错误.经过大量的谷歌搜索,我仍然没有设法让它工作,任何帮助将不胜感激:)
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 to deal with cleaning up files. Below is my code and my error. After much googling I still have not managed to 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 = "
".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('
' + team_name + ' Email Sent')
错误:
<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:oppssupold_jobqueue_cleaner_functions.py", line 179, in email_sup_teams
msg.attach(attachment)
File "C:Python34libemailmime
onmultipart.py", line 22, in attach
'Cannot attach additional subparts to non-multipart/*')
email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/*
推荐答案
原来我应该读过
更紧密.我很确定这是因为我只使用 1 个 MIME 类型对象来构建我的电子邮件,但尝试添加多个 MIME 对象.基本上为了让它工作,我使用了下面的代码.快乐的日子!
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 = "
".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('
' + team_name + ' Email Sent')
这篇关于将对象之类的文件附加到电子邮件python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!