我正在尝试发送示例电子邮件,但收到以下错误:
>>> import smtplib
>>> from email.mime.text import MIMEText
>>> def send_email(subj, msg, from_addr, *to, host="localhost", port=1025, **headers):
... email = MIMEText(msg)
... email['Subject'] = subj
... email['From'] = from_addr
... for h, v in headers.items():
... print("Headers - {} Value {} ".format(h, v))
... email[h] = v
... sender = smtplib.SMTP(host,port)
... for addr in to:
... del email['To']
... email['To'] = addr
... sender.sendmail(from_addr, addr, email.as_string())
... sender.quit()
...
>>> headers={'Reply-To': 'me2@example.com'}
>>> send_email("first email", "test", "first@example.com", ("p1@example.com", "p2@example.com"), headers=headers)
Headers - headers Value {'Reply-To': 'me2@example.com'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in send_email
File "/usr/lib/python3.5/email/message.py", line 159, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python3.5/email/generator.py", line 115, in flatten
self._write(msg)
File "/usr/lib/python3.5/email/generator.py", line 195, in _write
self._write_headers(msg)
File "/usr/lib/python3.5/email/generator.py", line 222, in _write_headers
self.write(self.policy.fold(h, v))
File "/usr/lib/python3.5/email/_policybase.py", line 322, in fold
return self._fold(name, value, sanitize=True)
File "/usr/lib/python3.5/email/_policybase.py", line 360, in _fold
parts.append(h.encode(linesep=self.linesep,
AttributeError: 'dict' object has no attribute 'encode'
当我省略可选的标题字典时,电子邮件已成功发送。 ** param需要一本字典,这是正确的吗? 任何人都可以为错误提出补救措施吗?
答案 0 :(得分:1)
您误解了*args
和**kwargs
的工作原理。它们捕获额外的位置和关键字参数,同时分别传递一个额外的元组和一个额外的字典(...)
和headers=headers
。
这意味着to
现在设置为(("p1@example.com", "p2@example.com"),)
(包含单个元组的元组),headers
设置为{'headers': {'Reply-To': 'me2@example.com'}}
(包含另一个字典的字典)
你在输出中看到后者:
Headers - headers Value {'Reply-To': 'me2@example.com'}
这是headers
键,引用字典。
将to
值作为单独的参数传递,并使用**kwargs
调用语法传入标题:
headers={'Reply-To': 'me2@example.com'}
send_email("first email", "test",
"first@example.com", "p1@example.com", "p2@example.com",
**headers)
**headers
将该字典中的每个键值对作为单独的关键字参数应用。