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

Send csv-file as attachment via MIMEBase - python

我不明白。我尝试发送一封带有 csv 文件作为附件的电子邮件。带有脚本的第一个 运行 很好,我收到了带有 csv 文件附件的电子邮件。但是在 运行ning 一次之后,脚本崩溃并出现一条奇怪的 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'>

有什么想法吗?

奇怪,当我这样做时

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

而不是

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

代码有效。仍然想知道为什么...!?