Boost Email Delivery Speed with PHP Async Coroutines

This article explains how to use PHP asynchronous coroutines with Swoole and PHPMailer to concurrently send large volumes of emails, improving performance, stability, and resource usage compared to traditional synchronous mailing methods.

php Courses
php Courses
php Courses
Boost Email Delivery Speed with PHP Async Coroutines

1. Introduction to PHP Async Coroutines

In modern web applications, sending emails (for registration verification, order confirmation, password reset, etc.) is essential, but synchronous sending becomes inefficient and unstable when handling large volumes. PHP async coroutines leverage an event‑loop to execute multiple tasks concurrently on a single thread, reducing resource overhead.

2. Principle of Optimizing Email Sending

Traditional email sending is synchronous: each email must finish before the next starts, leading to long delays and high server load under heavy traffic. By wrapping each send operation in an async coroutine, many emails can be dispatched in parallel, eliminating wait time and improving overall stability.

3. Code Example Using PHP Async 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); // wait for all emails to finish
    swoole_event_exit(); // exit event loop
});

4. Explanation of the Implementation

The sendMail function creates a PHPMailer instance and configures SMTP settings. It runs inside a go coroutine, so the call returns immediately while the actual sending proceeds asynchronously.

A Channel is used to queue email data. One coroutine fills the channel with 100 test messages, then closes it. Another coroutine consumes the channel, invoking sendMail for each entry, achieving concurrent dispatch.

Finally, a coroutine sleeps briefly to ensure all send operations complete before calling swoole_event_exit() to terminate the event loop.

5. Conclusion

Using PHP async coroutines with Swoole dramatically speeds up bulk email delivery, reduces server load, and improves application responsiveness. Developers can adapt the provided example to their own SMTP settings and scaling requirements.

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.

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