2015-04-27 124 views
1

我正在使用Python 3.4中的smtplib和电子邮件模块发送电子邮件。Python smtplib send_message()失败,返回AttributeError:'str'对象没有属性'get_all'

我能够创建电子邮件本身和我能够连接到服务器,但随后返回此异常:

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 - 不知道是否会影响到这一点。

有谁知道是什么原因导致了这个错误?

编辑原来我的问题的一部分是我使用的格式不正确。 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' 

回答

4

SMTP.send_message签名是不一样的SMTP.sendmail。因此,尝试:

server.send_message(msg, fromaddr, toaddrs) 

编辑

您还需要单独添加To:头,而不是作为一个列表:

for item in input("To: ").split(): 
     msg['To'] = item 
+0

感谢您指出了这一点,我已经错过了区别。我没有得到那个错误了,但我现在得到这个错误:'AttributeError:'list'object has no attribute'encode''。我会用完整的回溯来更新我的问题。 –

+0

没关系,只是想出了我自己的新错误。它是由msg ['To'] = input()。split()'行引起的,因为它接受输入并生成一个列表。谢谢,接受你的答案。 –

+0

@RPiAwesomeness。是的:你需要分别添加每个项目(我已经更新了我的答案)。 – ekhumoro

相关问题