Backend Development 5 min read

Optimizing Email Sending with PHP Asynchronous Coroutines

This article explains how to use PHP asynchronous coroutines, powered by Swoole, to concurrently send large volumes of email, improving throughput and stability, and provides a complete code example with PHPMailer integration and channel-based task distribution.

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

In modern web applications, email delivery 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.

This guide introduces PHP asynchronous coroutines, which leverage an event‑loop mechanism to execute multiple tasks concurrently on a single thread, reducing resource overhead compared to multi‑thread or multi‑process approaches.

By wrapping email‑sending logic in a coroutine, multiple emails can be dispatched in parallel, eliminating the wait time of synchronous sends and lowering server load, thereby enhancing overall performance and reliability.

The following code demonstrates a complete implementation using Swoole coroutines and PHPMailer:

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); // wait for all emails to be sent
    swoole_event_exit(); // exit event loop
});

The sendMail function utilizes PHPMailer to perform the actual SMTP transmission, while the coroutine wrapper ensures non‑blocking execution.

A Swoole channel queues email payloads; one coroutine populates the channel, and another consumes the queue, invoking sendMail for each entry, achieving high concurrency.

Finally, a dedicated coroutine waits briefly before terminating the event loop, guaranteeing that all asynchronous tasks have completed.

Using PHP asynchronous coroutines thus accelerates email delivery, reduces server resource consumption, and improves application responsiveness, making it a valuable technique for backend developers handling bulk email scenarios.

backendasynchronousPHPCoroutineEmailSwoolePHPMailer
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.