2015-04-27 156 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

相關問題