Python EmailMessage创建邮件草稿时触发AttributeError: 'list' object has no attribute 'encode'错误求助
Python EmailMessage创建邮件草稿时触发AttributeError: 'list' object has no attribute 'encode'错误求助
我最近在实现邮件草稿创建功能时碰到了一个诡异的问题,明明传入的文本都是字符串,但调用msg.as_bytes()的时候却触发了列表没有encode方法的错误,实在搞不懂哪里出问题了,麻烦大家帮忙看看!
我的核心代码是这样的:
def _create_draft(sender, to, subject, msg_html, msg_plain, attachments): msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(msg_plain, 'plain')) msg.attach(MIMEText(msg_html, 'html')) if attachments: msg = _add_attachments(msg, attachments) return {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()}
触发的错误回溯信息如下:
File "/srv/www/code/project/email.py", line 56, in write_security_email send_message(from_address, to_address, subject, html_body, txt_body) File "/srv/www/code/project/gmail/gmail_api.py", line 52, in send_message msg = _create_draft(sender, to, subject, msgHtml, msgPlain, attachments) File "/srv/www/code/project/gmail/gmail_api.py", line 84, in _create_draft return {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()} File "/usr/lib/python3.8/email/message.py", line 178, in as_bytes g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python3.8/email/generator.py", line 116, in flatten self._write(msg) File "/usr/lib/python3.8/email/generator.py", line 181, in _write self._dispatch(msg) File "/usr/lib/python3.8/email/generator.py", line 218, in _dispatch meth(msg) File "/usr/lib/python3.8/email/generator.py", line 431, in _handle_text if _has_surrogates(msg._payload) and not self.policy.cte_type=='7bit': File "/usr/lib/python3.8/email/utils.py", line 57, in _has_surrogates s.encode() AttributeError: 'list' object has no attribute 'encode'
我观察到几个奇怪的现象:
- 当只发送纯文本邮件(不带附件)时,就会触发上面的错误。我确认
msg_html和msg_plain都是字符串,不是列表,甚至把它们直接替换成固定字符串"my string",还是会报错,而且attachments变量是None。 - 当发送带附件的邮件时,邮件能正常发送出去(但没有正文内容),不会触发错误。
- 如果把那两行
msg.attach(MIMEText(...))注释掉,邮件能发送,但同样没有正文。 - 在我添加附件功能之前,这段代码是能正常发送带正文的邮件的,肯定是我加附件功能时改了什么地方但忘了,可就是找不到问题所在。
实在是百思不得其解,有没有大佬能帮我找找问题出在哪里呀?非常感谢!
备注:内容来源于stack exchange,提问作者David Murphy
相关产品推荐
相关产品推荐

