将已解析的email.message.Message实例作为Python中的有效内容附加到创建的email.mime.multipart实例

时间:2012-11-09 12:11:22

标签: python email mime email-attachments

到目前为止,我还无法在stackexchange或Google上找到解决此特定问题的方法。

在Python中有很多将文件附加到多部分邮件的示例,但我想从已解析的邮件中提取附件,然后将其重新附加到新的多部分电子邮件

在我对文档进行解释之后,这就是我执行此任务的方式,在一个小的工作测试脚本中演示。

#!/usr/bin/env python

import sys
from email.parser import Parser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

email = Parser().parse(sys.stdin)

payloads = email.get_payload()

newMail = MIMEMultipart()
newMail['From'] = 'me@domain.tld'
newMail['Subject'] = 'Some subject'
newMail['To'] = 'someguy@ibm.com'
newMail.preamble = 'You need a MIME reader'

for p in payloads:
    p.add_header('Content-Disposition', 'attachment', filename='att.eml')
    newMail.attach(p)

body = MIMEText('This is some body')
newMail.attach(body)

o = open('testoutput', 'w')
o.write(newMail.as_string())
o.close()

sys.exit(0)

这实际上是一个成功的测试,当我检查生成的testoutput文件时看起来就像预期的那样。

然而,here's the code我正在努力工作,但它失败并显示以下消息。

Traceback (most recent call last):
  File "../devops/spam/spamutbildning.py", line 232, in <module>
    if main():
  File "../devops/spam/spamutbildning.py", line 127, in main
    messageText = newMail.as_string()
  File "/usr/lib/python2.6/email/message.py", line 135, in as_string
    g.flatten(self, unixfrom=unixfrom)
  File "/usr/lib/python2.6/email/generator.py", line 83, in flatten
    self._write(msg)
  File "/usr/lib/python2.6/email/generator.py", line 115, in _write
    self._write_headers(msg)
  File "/usr/lib/python2.6/email/generator.py", line 161, in _write_headers
    header_name=h, continuation_ws='\t').encode()
  File "/usr/lib/python2.6/email/header.py", line 403, in encode
    return self._encode_chunks(newchunks, maxlinelen)
  File "/usr/lib/python2.6/email/header.py", line 363, in _encode_chunks
    _max_append(chunks, s, maxlinelen, extra)
  File "/usr/lib/python2.6/email/quoprimime.py", line 97, in _max_append
    L.append(s.lstrip())
AttributeError: 'tuple' object has no attribute 'lstrip'

我不理解第127行的newMail.as_string()与我尝试用作字符串的元组之间的关系。

编辑:我无法回答我自己的问题,但我发现了问题。特别是在__setitem__对象中使用Message

它应该是这样的。

msg['from'] = 'from me'

我正在做的是什么,但是当我改用add_header时,它的效果要好得多。每当我使用短格式[..] = foo时,我得到了元组错误。

0 个答案:

没有答案