将文件像对象一样附加到电子邮件python 3

时间:2015-05-05 02:18:45

标签: file python-3.x smtp

我在网上找到了很多关于如何将本地文件附加到电子邮件的示例。我想要做的是将像对象这样的文件附加到电子邮件中。你为什么问?所以我不必处理清理文件。下面是我的代码和我的错误。经过大量的谷歌搜索,我仍然没有设法让它工作,任何帮助将不胜感激:)

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')

错误:

<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/*

1 个答案:

答案 0 :(得分:6)

原来我应该阅读

E-Mail Examples from Python Docs

更密切。我很确定它,因为我只使用一个MIME类型对象来构建我的电子邮件,但试图添加多个MIME对象。基本上为了让它工作我使用下面的代码。快乐的日子!

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')