image embedded in email HTML template - Flask-mail ValueError: too many values to unpack (expected 2)

image embedded in email HTML template - Flask-mail ValueError: too many values to unpack (expected 2)

我尝试从 HTML 模板发送回复电子邮件,其中包含 header 上的图像。如果我发送 HTML 没有图像附件,则没有错误,但它是一个文本电子邮件。我搜索测试了几天,没有成功。

Flask-email 片段是

msg = Message(form.title.data, recipients=['emial@gmail.com'])
msg.html = render_template('mail_temp/file.html')
with open('/home/daniel/PycharmProjects/Sitio/blue/static/pictures/ribbon.jpg', 'rb') as fp:
    msg.attach('ribbon.jpg', 'image/jpg', fp.read(), 'inline', headers={'Content-ID': 'ribbon'})
mail.send(msg)

HTML 模板包含图像在:

<td> <img src="cid:ribbon"/> </td>

问题似乎发生在 Message 的参数中。附上方法。我发现了一个类似的问题和回复,但已有 2 年历史,也许方法改变了它。

提前致谢。

  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/daniel/PycharmProjects/Sitio/blue/site/routes.py", line 220, in contactme
    mail.send(msg)
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 492, in send
    message.send(connection)
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 427, in send
    connection.send(self)
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 190, in send
    message.as_bytes() if PY3 else message.as_string(),
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 385, in as_bytes
    return self._message().as_bytes()
  File "/home/daniel/anaconda3/envs/Sitio/lib/python3.8/site-packages/flask_mail.py", line 371, in _message
    for key, value in attachment.headers:
ValueError: too many values to unpack (expected 2)
``

原来msg.attach参数有两个问题:

  1. headers 是一个列表而不是字典;
  2. Contend-ID 标签包含在 < >
with open('/home/daniel/PycharmProjects/Sitio/blue/static/pictures/ribbon.jpg', 'rb') as fp:
    msg.attach('ribbon.jpg', 'image/jpg', fp.read(), 'inline', headers=[[Content-ID','<ribbon>']])