1. Production-Ready aiosmtplib Script
import asyncio
import aiosmtplib
from email.message import EmailMessage
SMTP_HOST = "relay.171mails.com"
SMTP_PORT = 587
SMTP_USER = "your_171mails_username"
SMTP_PASS = "your_171mails_password"
CONCURRENCY_LIMIT = 10
semaphore = asyncio.Semaphore(CONCURRENCY_LIMIT)
async def send_single_email(client, recipient):
async with semaphore:
msg = EmailMessage()
msg["From"] = "updates@yourdomain.com"
msg["To"] = recipient
msg["Subject"] = "Important System Update"
msg.set_content("Hello, this is an authenticated high-speed delivery.")
await client.send_message(msg)
print(f"Delivered to {recipient}")
async def main(recipients):
client = aiosmtplib.SMTP(hostname=SMTP_HOST, port=SMTP_PORT, start_tls=True)
await client.connect()
await client.login(SMTP_USER, SMTP_PASS)
tasks = [send_single_email(client, r) for r in recipients]
await asyncio.gather(*tasks)
await client.quit()
# Run async loop
# asyncio.run(main(["user1@example.com", "user2@example.com"])) 2. The Danger of Unbounded Concurrency
If you create 5,000 asynchronous tasks without an asyncio.Semaphore, Python will attempt to open 5,000 simultaneous sockets, causing OS socket exhaustion (OSError: [Errno 24] Too many open files) and triggering destination firewall bans. Always bound concurrency between 5 and 15.
3. Integrating Celery for Distributed Python Workloads
In web applications (Django, FastAPI, Flask), offload sending to Celery task queues backed by Redis or RabbitMQ for automated retries and hourly throughput pacing.