Python smtplib send_message() failing, returning AttributeError: 'str' object has no attribute 'get_all'

Python smtplib send_message() failing, returning AttributeError: 'str' object has no attribute 'get_all'

我正在做一个项目,我必须使用 Python 3.4 中的 smtplib 和电子邮件模块来发送电子邮件。

我能够自己创建电子邮件并且能够连接到服务器,但是 returns 这个异常:

reply: b'235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: b'2.7.0 Accepted'
send: 'QUIT\r\n'
reply: b'221 2.0.0 closing connection s66sm8304113yhp.2 - gsmtp\r\n'
reply: retcode (221); Msg: b'2.0.0 closing connection s66sm8304113yhp.2 - gsmtp'
Traceback (most recent call last):
  File "base.py", line 108, in <module>
    send(fromaddr, toaddrs, msg)
  File "base.py", line 61, in send
    server.send_message(fromaddr, toaddrs, msg)
  File "/usr/lib/python3.4/smtplib.py", line 829, in send_message
    resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'

代码(麻烦的线路直接链接到)可用 here。奇怪的是,代码实际上在实际发送任何电子邮件正文之前发送 QUIT - 不确定这是否会影响它。

有谁知道导致此错误的原因吗?

EDIT 结果我的部分问题是我使用了不正确的格式。 send_message() 需要 Message, From, To 顺序的变量,而我的代码是按 From, To, Message.

的顺序发送的

但是,我现在收到此错误:

reply: b'235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: b'2.7.0 Accepted'
send: 'QUIT\r\n'
reply: b'221 2.0.0 closing connection s66sm8443316yhp.2 - gsmtp\r\n'
reply: retcode (221); Msg: b'2.0.0 closing connection s66sm8443316yhp.2 - gsmtp'
Traceback (most recent call last):
  File "MIME-base.py", line 108, in <module>
    send(fromaddr, toaddrs, msg)
  File "MIME-base.py", line 61, in send
    server.send_message(msg, fromaddr, toaddrs)
  File "/usr/lib/python3.4/smtplib.py", line 839, in send_message
    g.flatten(msg_copy, linesep='\r\n')
  File "/usr/lib/python3.4/email/generator.py", line 109, in flatten
    self._write(msg)
  File "/usr/lib/python3.4/email/generator.py", line 189, in _write
    self._write_headers(msg)
  File "/usr/lib/python3.4/email/generator.py", line 416, in _write_headers
    self._fp.write(self.policy.fold_binary(h, v))
  File "/usr/lib/python3.4/email/_policybase.py", line 325, in fold_binary
    folded = self._fold(name, value, sanitize=self.cte_type=='7bit')
  File "/usr/lib/python3.4/email/_policybase.py", line 352, in _fold
    parts.append(h.encode(linesep=self.linesep,
AttributeError: 'list' object has no attribute 'encode'

SMTP.send_message is not the same as SMTP.sendmail 的签名。所以尝试:

server.send_message(msg, fromaddr, toaddrs)

编辑:

您还需要将 To: headers 添加为字符串,而不是列表:

receivers = ['someone@abc.com', 'someone@xyz.com']
msg['To'] = ', '.join(receivers)