Sobes.tech
Junior — Middle

What multithreading method would you use for mass email sending?

sobes.tech AI

Answer from AI

For mass email sending in Python, multithreading with the concurrent.futures.ThreadPoolExecutor module is often used. This is because sending emails is an input/output (I/O) operation, and multithreading allows efficient utilization of waiting time for network operations.

Example:

from concurrent.futures import ThreadPoolExecutor
import smtplib

# Function to send a single email
def send_email(recipient):
    with smtplib.SMTP('smtp.example.com') as server:
        server.login('user', 'password')
        message = f"Subject: Hello\n\nThis is a test email for {recipient}"
        server.sendmail('from@example.com', recipient, message)

# List of recipients
recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com']

with ThreadPoolExecutor(max_workers=5) as executor:
    executor.map(send_email, recipients)

This approach allows parallel email sending without blocking the main thread, efficiently utilizing network resources. For larger-scale tasks, asynchronous libraries or task queues can be considered.