Backend Development 5 min read

Optimizing Email Sending with PHP Asynchronous Coroutines

This article explains how to improve the speed and stability of bulk email delivery in modern web applications by using PHP asynchronous coroutines, detailing the underlying principles, advantages over synchronous sending, and providing a complete code example with Swoole, PHPMailer, and channel coordination.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Optimizing Email Sending with PHP Asynchronous Coroutines

In modern web applications, email sending is essential for functions such as registration verification, order confirmation, and password reset, but traditional synchronous sending becomes inefficient and unstable when handling large volumes.

1. Introduction to PHP Asynchronous Coroutines

PHP asynchronous coroutines leverage an event‑loop mechanism to execute multiple tasks concurrently within a single thread, avoiding the resource overhead of multi‑thread or multi‑process approaches.

2. Principle of Optimizing Email Sending

Traditional synchronous email sending waits for each message to finish before proceeding, leading to long delays and high server load under bulk workloads. By encapsulating each send operation in a coroutine, many emails can be dispatched concurrently, improving throughput and stability.

3. Code Example Using PHP Asynchronous Coroutines

The following code demonstrates how to send emails with Swoole coroutines and PHPMailer, using a channel to distribute tasks and a final coroutine to wait for completion.

use SwooleCoroutine;
use SwooleCoroutineChannel;
use PHPMailerPHPMailerPHPMailer;

function sendMail($to, $subject, $body)
{
    go(function () use ($to, $subject, $body) {
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'username';
        $mail->Password = 'password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom('[email protected]');
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->Body = $body;

        if ($mail->send()) {
            echo "发送成功";
        } else {
            echo "发送失败:" . $mail->ErrorInfo . "";
        }
    });
}

$channel = new Channel();

go(function () use ($channel) {
    for ($i = 1; $i <= 100; $i++) {
        $channel->push(["[email protected]", "测试邮件{$i}", "这是一封测试邮件"]);
    }
    $channel->close();
});

go(function () use ($channel) {
    while ($data = $channel->pop()) {
        sendMail($data[0], $data[1], $data[2]);
    }
});

Coroutine::create(function () {
    Coroutine::sleep(1); // 等待所有邮件发送完成
    swoole_event_exit(); // 退出事件循环
});

The sendMail function creates a PHPMailer instance and sends a single email. A Channel is populated with 100 email payloads, which are then consumed by a second coroutine that calls sendMail for each entry.

Finally, a coroutine sleeps briefly to ensure all sends finish before exiting the event loop.

4. Conclusion

Using PHP asynchronous coroutines can significantly boost email sending speed and reliability, reduce server resource consumption, and enhance overall application performance, providing a practical pattern for developers needing high‑throughput mail delivery.

backendasynchronousPHPcoroutinesEmailSwoolePHPMailer
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.