Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send asynchronous mail?

Tags:

php

It will take time to send the mail to the user and executing the code up to the Location header. I want to run the mail sending code in another thread so it will not take time to locate or load that particular page.

$sql = "SELECT email FROM user_info where username = ?";

        $statement = $db->prepare($sql);
        $statement->bindParam(1, $cmtTo);
        $statement->execute();

        $row = $statement->fetch();

//        echo $row['email'];

        $mailSender = new PuzzleEmailSender();
        $body = "<html>
                    <body>
            <h2 style=\"font-weight:bold;font-size:24px;font-family:Helvetica,Arial,sans-serif;line-height:26px;color:#999;margin:0\"><img class=\"navbarimg\"  src=\"" alt=\"/></h2><br>
                            <div style=\"font:normal 14px Helvetica,Arial,sans-serif;line-height:19px;color:#333\">
                <p>Hi, <strong>" . $cmtTo . "</strong> </p>
                                <p><strong>" . $cmtBy . "</strong> expressed comment on your puzzle answer</strong></p>
                <p><a style=\"text-decoration:underline;color:#00aff0;font-weight:bold\" href='" "' target=\"_blank\">Click on the link to check</a></p>                                
                <p>Team,</p>
                <p style=\"font-weight:bold;font-size:15px;line-height:24px;font-family:Arial,Helvetica,sans-serif;color:#666;margin:0\">
                " "</p></div>
                            </div>
                    </body>
        </html>";

        $subject = "Comment On Your Answer";

        $mailSender->sendQueryEmail($row['email'], "", $body, $subject, "", false);

        header("Location: puzzleDisplay");
like image 718
Pallavi Avatar asked Mar 23 '26 03:03

Pallavi


1 Answers

create table: mail_queue

fields: id, email, subject, body

change:

$mailSender->sendQueryEmail($row['email'], "", $body, $subject, "", false);

to

$sql = "INSERT INTO mail_queue SET email = ?, body = ?, subject = ?"
$statement = $db->prepare($sql);
$statement->bindParam(1, $row['email']);
$statement->bindParam(2, $body);
$statement->bindParam(3, $subject);
$statement->execute();

create script: mail_queue.php that will do fetch all emails and do mail send and then delete record after send

put to crontab: * * * * * php mail_queue.php

like image 65
num8er Avatar answered Mar 25 '26 20:03

num8er