首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Asyncio获取邮件python3

Asyncio获取邮件python3
EN

Stack Overflow用户
提问于 2014-07-30 13:32:10
回答 2查看 4K关注 0票数 8

我正在用异步模块进行测试,但是我需要提示/建议如何以异步方式获取大型电子邮件。

我有一个包含邮件帐户用户名和密码的列表。

代码语言:javascript
复制
data = [
    {'usern': 'foo@bar.de', 'passw': 'x'},
    {'usern': 'foo2@bar.de', 'passw': 'y'},
    {'usern': 'foo3@bar.de', 'passw': 'z'} (...)
]

我想:

代码语言:javascript
复制
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([get_attachment(d) for d in data]))
loop.close()

然而,很长的一部分是下载电子邮件附件。

电子邮件:

代码语言:javascript
复制
@asyncio.coroutine
def get_attachment(d):
    username = d['usern']
    password = d['passw']

    connection = imaplib.IMAP4_SSL('imap.bar.de')
    connection.login(username, password)
    connection.select()

    # list all available mails
    typ, data = connection.search(None, 'ALL')

    for num in data[0].split():
        # fetching each mail
        typ, data = connection.fetch(num, '(RFC822)')
        raw_string = data[0][1].decode('utf-8')
        msg = email.message_from_string(raw_string)
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue

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

            if part.get_filename():
                body = part.get_payload(decode=True)
                # do something with the body, async?

    connection.close()
    connection.logout()

我如何以异步方式处理所有(下载附件)邮件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-30 14:19:23

如果您没有基于异步I/O的imap库,您可以只使用concurrent.futures.ThreadPoolExecutor在线程中执行I/O。Python将在I/O期间发布GIL,因此您将获得真正的并发性:

代码语言:javascript
复制
def init_connection(d):    
    username = d['usern']
    password = d['passw']

    connection = imaplib.IMAP4_SSL('imap.bar.de')
    connection.login(username, password)
    connection.select()
    return connection

local = threading.local() # We use this to get a different connection per thread
def do_fetch(num, d, rfc):
    try:
        connection = local.connection
    except AttributeError:
        connnection = local.connection = init_connection(d)
    return connnection.fetch(num, rfc)

@asyncio.coroutine
def get_attachment(d, pool):
    connection = init_connection(d)    
    # list all available mails
    typ, data = connection.search(None, 'ALL')

    # Kick off asynchronous tasks for all the fetches
    loop = asyncio.get_event_loop()
    futs = [asyncio.create_task(loop.run_in_executor(pool, do_fetch, num, d, '(RFC822)'))
                for num in data[0].split()]

    # Process each fetch as it completes
    for fut in asyncio.as_completed(futs):
        typ, data = yield from fut
        raw_string = data[0][1].decode('utf-8')
        msg = email.message_from_string(raw_string)
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue

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

            if part.get_filename():
                body = part.get_payload(decode=True)
                # do something with the body, async?

    connection.close()
    connection.logout()    


loop = asyncio.get_event_loop()
pool = ThreadPoolExecutor(max_workers=5)  # You can probably increase max_workers, because the threads are almost exclusively doing I/O.
loop.run_until_complete(asyncio.wait([get_attachment(d, pool) for d in data]))
loop.close()

这并不像真正基于异步I/O的解决方案那么好,因为您仍然有创建线程的开销,这限制了可伸缩性并增加了额外的内存开销。由于所有包装实际I/O调用的代码,您也会遇到一些GIL减速。尽管如此,如果你处理的邮件少于数千封,它的表现应该还不错。

我们使用run_in_executor作为异步事件循环的一部分使用ThreadPoolExecutor,使用asyncio.async包装在asyncio.Future中返回的coroutine对象,并使用as_completed按照它们完成的顺序迭代未来。

编辑

看起来imaplib并不是线程安全的。我已经编辑了我的答案,通过threading.local使用线程本地存储,它允许我们每个线程创建一个连接对象,它可以在线程的整个生命周期中被重用(这意味着您只创建num_workers连接对象,而不是为每个fetch创建一个新连接)。

票数 7
EN

Stack Overflow用户

发布于 2016-07-05 14:44:50

我也有同样的需求:用python 3完全异步获取电子邮件。如果这里的其他人感兴趣,我在这里推出了异步IMAP库:https://github.com/bamthomas/aioimaplib

你可以这样使用它:

代码语言:javascript
复制
import asyncio
from aioimaplib import aioimaplib

@asyncio.coroutine
def wait_for_new_message(host, user, password):
    imap_client = aioimaplib.IMAP4(host=host)
    yield from imap_client.wait_hello_from_server()

    yield from imap_client.login(user, password)
    yield from imap_client.select()

    asyncio.async(imap_client.idle())
    id = 0
    while True:
        msg = yield from imap_client.wait_server_push()
        print('--> received from server: %s' % msg)
        if 'EXISTS' in msg:
            id = msg.split()[0]
            imap_client.idle_done()
            break

    result, data = yield from imap_client.fetch(id, '(RFC822)')
    email_message = email.message_from_bytes(data[0])

    attachments = []
    body = ''
    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get_content_maintype() == 'text' and 'attachment' not in part.get('Content-Disposition', ''):
            body = part.get_payload(decode=True).decode(part.get_param('charset', 'ascii')).strip()
        else:
            attachments.append(
                {'type': part.get_content_type(), 'filename': part.get_filename(), 'size': len(part.as_bytes())})

    print('attachments : %s' % attachments)
    print('body : %s' % body)
    yield from imap_client.logout()



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(wait_for_new_message('my.imap.server', 'user', 'pass'))

带有附件的大型电子邮件也是通过异步下载的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25038204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档