电子邮件可选标题错误

时间:2016-09-04 10:35:35

标签: python python-3.x smtplib

我正在尝试发送示例电子邮件,但收到以下错误:

>>> 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需要一本字典,这是正确的吗? 任何人都可以为错误提出补救措施吗?

1 个答案:

答案 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将该字典中的每个键值对作为单独的关键字参数应用。

相关问题