第 6 章 SendGrid 发送 HTML 邮件报错 AttributeError:list object has no attrribute _type 的解决方法

sendgrid

#1

sendgrid-python 最近几个版本破坏性变动比较大,changelog 写的乱七八糟。对于 6.3.1 中的代码块:

from sendgrid.helpers.mail import Email, Content, Mail

# ...
text_content = Content("text/plain", "纯文本正文")
html_content = Content("text/html", "<h1>HTML正文</h1>")
mail = Mail(from_email, subject, to_email, content=[text_content, html_content])

如果你运行时遇到了 AttributeError:list object has no attrribute _type 错误,有下面几种解决方法:

  1. 回退 sendgrid 库到 5.3.0 版本。
  2. 修改代码实现,改为(下一次重印将会采用下面的实现):
from sendgrid.helpers.mail import Email, Content, Mail

# ...
text_content = Content("text/plain", "纯文本正文")
html_content = Content("text/html", "<h1>HTML正文</h1>")
mail = Mail(from_email, subject, to_email, content=text_content)
mail.add_content(html_content)

顺便说一下,未来会发布的 v4 版本 API,用法又将变成:

from sendgrid.helpers.mail import Email, Content, Mail

# ...
text_content = Content("text/plain", "纯文本正文")
html_content = Content("text/html", "<h1>HTML正文</h1>")
mail = Mail(from_email, subject, to_email, plain_text_content=text_content, html_content=html_content])