python批量发送邮件,通知

1. run_in_executer

import asyncio
import time

def sync_send_email():
    time.sleep(2)
    return "Done"

async def send_email():
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, sync_send_email)  # 扔进线程池执行
    print(result)

asyncio.run(send_email())

2. 用asyncio.to_thread同步转异步‘

若是已经写好了同步发送邮件,则可以通过asyncio.to_thread同步转为异步发送

import asyncio
import time

def send_email():
    time.sleep(2)
    return "Done"

async def async_send_email():
    result = await asyncio.to_thread(send_email)  # 一行搞定!
    print(result)

asyncio.run(async_send_email())

3. 通过httpx异步发送邮件

异步直接实现发送邮件可以通过httpx实现,如下

async def async_send_email():
    async with httpx.AsyncClient(verify=False) as client:
        response = await client.post(
            f"https://{settings.domain}/email",
            json=data,
            cookies=cookies,
        )

4. 用信号量控制并发

# 用信号量(asyncio.Semaphore)控制并发
async def run_with_limit(task_func, max_cnotallow=50):
    semaphore = asyncio.Semaphore(max_concurrency)
    async def wrapper():
        async with semaphore:
            return await asyncio.to_thread(task_func)
    return wrapper

async def send_batch_email():
    tasks = [run_with_limit(send_one_email)() for _ in range(1000)]
    await asyncio.gather(*tasks)

asyncio.run(send_batch_email())
  • 5. thread

thread = threading.Thread(func, *args)
thread.join()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值