Search code examples
phpphpmailer

Sending mail in PHP via Mail::factory sometimes will timeout my page


I am a JS developer so PHP is really not my expertise. I have a page that sends an email when submitted, sometimes the page will timeout when gmail servers are slow to respond.

I am wondering if there is a way to either extend the timeout of a page (I am using LAMP setup, Apache, PHP) or maybe run Mail::factory in aysnc non blocking?

or any other ideas to make sure the page does not timeout to users (I don't mind if they need to wait 10 more seconds as they see loading bar...) when gmail is slow to reply back?

this is the function

function sendMail($from, $to, $subject, $body, $type = "HTML", $attach = "", $attachType = "'image/jpg'") {

       $crlf = "\n";
       $mime = new Mail_mime(array('eol' => $crlf));

        #if ($type == "text") {
        # $mime->setTXTBody($body);
        #} else {
        $mime->setHTMLBody($body);
        #}

        $headers = array(
            'From' => "<from.gmail.com>",
            'To' => $to,
            'Subject' => $subject
        );

        $smtp = Mail::factory('smtp', array(
                'host' => 'ssl://smtp.gmail.com',
                'port' => '465',
                'auth' => true,
                'username' => '[email protected]',
                'password' => 'xxxx'
            ));

         //$to = 'Recipient Name <[email protected]>';

        $headers = $mime->headers($headers);
        $mail = $smtp->send($to, $headers, $body);


    if (PEAR::isError($mail)) {
      //echo("<p>" . $mail->getMessage() . "</p>");
     } else {
      //echo("<p>Message successfully sent!</p>");
     }
}

Thanks,

Sean.


Solution

  • You can remove execution timeout completely limit by adding

    set_time_limit(0);
    

    At the very top of your script.

    Here is the link to PHP documentation on this function.