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 with Swoole, providing a detailed code example that leverages PHPMailer, channels, and coroutine management.

php Courses
php Courses
php Courses
Optimizing Email Sending with PHP Asynchronous Coroutines

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

PHP asynchronous coroutines use an event‑loop mechanism to execute multiple tasks concurrently, allowing a single thread to handle many operations without the heavy resource overhead of multi‑threading or multi‑processing.

By encapsulating email‑sending tasks into coroutines, multiple emails can be dispatched concurrently, eliminating the wait time of synchronous sending and reducing server load.

The following code demonstrates how to send emails using PHP asynchronous coroutines:

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 "发送成功<br/>";
        } else {
            echo "发送失败:" . $mail->ErrorInfo . "<br/>";
        }
    });
}

$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 code first defines a sendMail function that uses the PHPMailer library to send an email inside a coroutine, ensuring non‑blocking execution.

A Channel is created to queue email data; one coroutine pushes 100 email tasks into the channel, while another coroutine pulls each task and calls sendMail to dispatch the emails concurrently.

Finally, a coroutine waits briefly to allow all sends to finish and then exits the Swoole event loop, completing the asynchronous workflow.

Using PHP asynchronous coroutines thus speeds up email delivery, improves stability, reduces server resource consumption, and enhances overall application performance, providing developers with a practical pattern for high‑throughput email services.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.