通过MIMEBase-python发送csv文件作为附件

时间:2015-02-12 14:59:42

标签: email python-2.7 csv mime-types attachment

我不明白。我尝试发送带有csv文件作为附件的电子邮件。第一次使用脚本运行很好,我收到了带有csv文件作为附件的电子邮件。但是在运行一次后,脚本会以奇怪的Traceback消息崩溃。

到目前为止我的代码:

import smtplib
import email.utils
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import Encoders

msg = MIMEMultipart('foo')
msg['To'] = email.utils.formataddr(('foo', 'foo@foobar.de'))
msg['From'] = email.utils.formataddr(('foo', 'foo@foo'))
msg['Subject'] = 'foo'

# Attach a file

mail_file = file('foo.csv').read()

mail_file = MIMEBase('application', 'csv')
mail_file.set_payload(mail_file)
mail_file.add_header('Content-Disposition', 'attachment', filename='foo.csv')
Encoders.encode_base64(mail_file)
msg.attach(mail_file)

# Define SMTP server

server = smtplib.SMTP('localhost')
server.set_debuglevel(True) # show communication with the server

# Send the mail

try:
    server.sendmail('foo@foo', ['foo@foobar.de'], msg.as_string())
finally:
    server.quit()

现在我得到以下追溯:

Traceback (most recent call last):
File "mail.py", line 27, in <module>
    Encoders.encode_base64(mail_file)
File "/usr/lib/python2.7/email/encoders.py", line 45, in encode_base64
    encdata = _bencode(orig)
File "/usr/lib/python2.7/email/encoders.py", line 31, in _bencode
    hasnewline = (s[-1] == '\n')
File "/usr/lib/python2.7/email/message.py", line 294, in __getitem__
    return self.get(name)
File "/usr/lib/python2.7/email/message.py", line 360, in get
    name = name.lower()
AttributeError: 'int' object has no attribute 'lower'

当我取消注释第27行(编码行)时,我得到以下内容:

Traceback (most recent call last):
File "mail.py", line 33, in <module>
  server.sendmail('foo@foo', ['foo@foobar.de'], msg.as_string())

File "/usr/lib/python2.7/email/message.py", line 137, in as_string
  g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
  self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
  self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 134, in _dispatch
  meth(msg)
File "/usr/lib/python2.7/email/generator.py", line 203, in _handle_multipart
  g.flatten(part, unixfrom=False)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
  self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
  self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 134, in _dispatch
  meth(msg)

File "/usr/lib/python2.7/email/generator.py", line 177, in _handle_text
  raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: <type 'instance'>

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

奇怪,当我做的时候

mail_file.set_payload(open('foo.csv', 'rb').read())

而不是

mail_file = file('foo.csv').read()
mail_file.set_payload(mail_file)

守则有效..仍然想知道为什么......!?