0

I'm trying to use Sendgrid PHP API (https://github.com/sendgrid/sendgrid-php) to send emails from a php loop. However, the script will only send the first email, and the loop will not continue.

I have a mail function defined like this:

function sendgrid($assoc_number,$to_email,$subject,$message,$HTML_message,$type) {
    require "sendgrid-php/sendgrid-php.php";


    $sendgrid = new SendGrid("api-key-removed");

    $email = new SendGrid\Email();
    $email
    ->setSmtpapiTos($to_email)
    ->setFrom($from_email)
    ->setSubject($subject)
    ->setText($message)
    ->setHtml($HTML_message)
    ->setCategories($type);
    ;

    $sendgrid->send($email);
}

The real loop is much more complicated, but this also stalls after sending the first mail:

$assoc_number = 10;
$to_email = array("me@mydomain.ca");
$subject = "Testing SendGrid loop";
$message = "Testing SendGrid loop.";
$HTML_message = "Testing <strong>SendGrid</strong> loop.";
$type = array("Test");

$i = 0;
while ($i<3) {
    $i++;
    sendgrid($assoc_number,$to_email,$subject,$message,$HTML_message,$type);
    echo $i . "<br>";
}

Any hints on why the loop stalls after the first email is sent?

  • You should [enable error reporting](http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) to see if there is an error happening on the first loop. Also, for a library file like this, you'll want to place the require statement outside of any function, often at the top of the script. You only need to load it once. – larsAnders Apr 07 '16 at 05:48
  • @larsAnders Thank you! Moving the require statement outside of the function has solved the problem. Unfortunately it means I'll have to include the Sendgrid library in the general functions file that's included on every page, or else add it to every php page that calls the mail function. It's a sprawling and primitive website that I've inherited. Glad to have it working though. – Approval Junkie Apr 07 '16 at 06:53

0 Answers0