gpt4 book ai didi

python - 将附件添加到电子邮件消息会引发 TypeError : set_text_content() got an unexpected keyword argument 'maintype'

转载 作者:行者123 更新时间:2023-12-01 00:49:09 24 4
gpt4 key购买 nike

按照Python email examples中的示例进行操作看起来添加附件应该非常简单。但是,以下方法不起作用:

import smtplib
from email.message import EmailMessage
import json

# Initialize message.
msg = EmailMessage()
msg['Subject'] = 'Testing, testing 1-2-3'
msg['To'] = 'fake@example.com'
msg['From'] = 'extrafake@example.com'
msg.set_content('Trying to attach a .json file')

# Create json attachment.
attachment = json.dumps({'This': 'is json'})

# Attempt to attach. This raises an exception.
msg.add_attachment(attachment, maintype='application', subtype='json', filename='test.json')

异常(exception)情况如下:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.7/email/message.py", line 1147, in add_attachment
self._add_multipart('mixed', *args, _disp='attachment', **kw)
File "/usr/local/lib/python3.7/email/message.py", line 1135, in _add_multipart
part.set_content(*args, **kw)
File "/usr/local/lib/python3.7/email/message.py", line 1162, in set_content
super().set_content(*args, **kw)
File "/usr/local/lib/python3.7/email/message.py", line 1092, in set_content
content_manager.set_content(self, *args, **kw)
File "/usr/local/lib/python3.7/email/contentmanager.py", line 37, in set_content
handler(msg, obj, *args, **kw)
TypeError: set_text_content() got an unexpected keyword argument 'maintype'

请注意,这非常接近第三个示例 here ,但失败了。知道如何附加 json 文件吗?

另请注意this answer提出了类似的工作流程,但使用相同的参数调用相同的函数,因此不能解决我的问题。

最佳答案

EmailMessage.set_content代表参加 ContentManager ,作为参数传递或默认 raw_data_manager .

raw_data_manager.set_content如果内容是 bytes,则接受 maintype 参数,但如果内容是 str,则不接受

因此解决方案是将 bytes 实例传递给 EmailMessage.set_content:

# Create json attachment.
attachment = json.dumps({'This': 'is json'})

# Encode to bytes
bs = attachment.encode('utf-8')

# Attach
msg.add_attachment(bs, maintype='application', subtype='json', filename='test.json')

关于python - 将附件添加到电子邮件消息会引发 TypeError : set_text_content() got an unexpected keyword argument 'maintype' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com