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 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 "发送成功
";
        } 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 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.

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.