Discuss / Python / 小结:

小结:

Topic source

出现问题: 我的邮件附件里的txt文本,不会被当做attachment,而会进入

if content_type == 'text/plain' or content_type == 'text/html':

这句判断下,而且guess_charset失败,guess不出来= =
结果如下:

part 1
charset:  None
    Text: b'\xd6\xae\xc7\xb0\xa3\xba20461 3429 31612\r\n\xd6\xae\xba\xf3\xa3\xba16062  3435 27375\r\n\xd4\xd9\xb2\xe2\xa3\xba19787  3458 31309\r\n\xb2\xf0\xb2\xe2\xa3\xba22373'
'''

分析: text文件里没有headers,当然guess不出来。所以问题是它怎么会被认为不是附件呢, 原因是包含这个text文件的MIME使用get_content_type()方法时返回了'text/plain',但get_charset()却返回了空。 包含text附件的MIME的headers如下:

>>> part._headers
[('Content-Type', 'text/plain; name="=?UTF-8?Q?=E6=95=A3=E7=83=AD.txt?="'), ('Content-Transfer-Encoding', 'base64'), ('Content-Disposition', 'attachment;\r\n filename="=?UTF-8?Q?=E6=95=A3=E7=83=AD.txt?="')]

对比表示正文的MIME的headers如下:

>>> part00._headers
[('Content-Type', 'text/plain; charset=UTF-8'), ('Content-Transfer-Encoding', 'base64')]

解决方法:

if content_type == 'text/plain' or content_type == 'text/html':

老师这句的逻辑目的是判断是否是正文,在它之前先判断附件用查找header 'Content-Disposition'的值是否含有'attachment'关键词,如下:

if 'attachment' in msg.get('Content-Disposition',''):
print('%sAttachment: %s' % ('    ' * indent, content_type))
elif msg.get_content_maintype() == 'text':
...

测试通过。

WOWsapling

#2 Created at ... [Delete] [Delete and Lock User]

问下:是什么邮箱发送到什么邮箱产生的。谢谢。


if content_type == 'text/plain' or content_type == 'text/html':

    ...

else:

    print('%sAttachment: %s' % ('  ' * indent, content_type))

老师的这句是判断是否是正文,否则为附件,如果附件是txt文本就可能是误判了,能否直接改成:

if 'attachment' not in msg.get('Content-Disposition',''):
    ...
else:
    print('%sAttachment: %s' % ('  ' * indent, content_type))

  • 1

Reply