我正在开发一个项目,我必须使用Python 3.4中的smtplib和电子邮件模块发送电子邮件。
我能够自己创建电子邮件,并且我能够连接到服务器,但之后它会返回此异常:
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'
答案 0 :(得分:7)
SMTP.send_message
的签名与SMTP.sendmail
不同。所以试试:
server.send_message(msg, fromaddr, toaddrs)
修改强>:
您还需要单独添加To:
标题,而不是列表:
for item in input("To: ").split():
msg['To'] = item