I am working on trying to set up scheduling for Sendgrid. I am new at working with sendgrid so am learning as I go.
The code I have works fine if there is only one email that is generated from the loop, but if multiple emails are present, then it just sends emails immediately.
require '../sendgrid/vendor/autoload.php'; // If you're using Composer (recommended)
use SendGrid\Mail\From;
use SendGrid\Mail\HtmlContent;
use SendGrid\Mail\Mail;
use SendGrid\Mail\PlainTextContent;
use SendGrid\Mail\To;
use SendGrid\Mail\SendAt;
use SendGrid\Mail\BatchId;
$from = new From("email", "name");
$sql1 = "SELECT * from database where sent='no'";
$tos=array();
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
$first= $row1["first"];
$last= $row1["last"];
$date= $row1["date"];
$email=$row1['email'];
$tos[]= new To(
"$email",
"$first $last",
[
'{{First_Name}}' => $first,
'{{Last_Name}}' => $last,
'{{testing}}' => $date,
'{{email}}' => $email,
],
"View your Testing Report Card!"
);
}
}
$globalSubstitutions = [
'-time-' => "2018-05-03 23:10:29"
];
$plainTextContent = new PlainTextContent(
"Good Morning!<br>
<br>
{{First_Name}}'s report card from the {{testing}} testing is ready to view.<br>
<br>
Please click the link below to view. <br>
<br>Login with the following:<br>
Name: {{First_Name}}<br>
Email: {{email}}.<br>
<br>
"
);
$htmlContent = new HtmlContent(
"Good Morning!<br>
<br>
{{First_Name}}'s report card from the {{testing}} testing is ready to view.<br>
<br>
Please click the link below to view. <br>
<br>Login with the following:<br>
Name: {{First_Name}}<br>
Email: {{email}}.<br>
<br>
"
);
$sendgrid = new \SendGrid('apikey');
try {
$response = $sendgrid->client->mail()->batch()->post();
print $response->statusCode() . "\n";
print_r($response->headers());
$batch= $response->body() . "\n";
echo $batch."<br>
<br>
<br>
";
} catch (Exception $ex) {
echo 'Caught exception: '. $ex->getMessage();
}
$data = json_decode($batch);
$batchnew= $data->batch_id;
$sendtime=strtotime("today 9:02");
$email = new Mail(
$from,
$tos,
$subject, // or array of subjects, these take precedence
$plainTextContent,
$htmlContent,
$globalSubstitutions
);
$email->setSendAt($sendtime);
$email->setBatchId($batchnew);
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage(). "\n";
}
This is the code I have so far. I think I have to create a batch in order to make this work…but I am not positive on that (maybe I don’t). I have noticed that if I use the above code, say I have 5 email addresses, it will schedule one of them but the others it sends right away. Any help would be appreciated!