使用imaplib从邮件获取android附件

时间:2012-02-20 17:15:13

标签: android python imap

我可以阅读我测试的所有电子邮件客户端发送的附件,除了androids默认电子邮件应用。它通过android中的gmail应用程序工作。

以下是一些代码:

import email as emaillib

result, data = imap_conn.uid('fetch', email_id, '(RFC822)')
raw_email = data[0][1]

get_attachments(emaillib.message_from_string(raw_email))

def get_attachments(email_message_instance):
    attachments = []
    for part in email_message_instance.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        data = part.get_payload(decode=True)
        if not data:
            continue
        filename = part.get_filename()

        print 'appending attachment with filename: ', filename
        attachments.append((filename, data))

    return attachments

当我从android中的默认电子邮件应用程序发送一个附件时,它会打印:

appending attachment with filename: None
appending attachment with filename: None
appending attachment with filename: =?utf-8?B?SU1BRzAxOTMuanBn?=

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好的我解决了这个问题,似乎我的Android默认邮件应用程序为所有内容写了内容处理。

文件名也是邪恶的。

所以我解决了问题(因为我只对媒体附件感兴趣):

from email.header import decode_header
    def get_attachments(email_message_instance):
        attachments = []
        for part in email_message_instance.walk():

            if part.get_content_maintype() not in ['image', 'video', 'audio']:
                continue

            if part.get('Content-Disposition') is None:
                continue

            data = part.get_payload(decode=True)
            if not data:
                continue

            filename = part.get_filename()      
            filename =  u' '.join(w.decode(e or 'ascii') for w,e in decode_header(filename))        
            attachments.append((filename, data))

        return attachments