Skip to content

Instantly share code, notes, and snippets.

@purdy
Last active September 15, 2017 02:40
Show Gist options
  • Save purdy/197a210480bcfe244d0b9277034d1b77 to your computer and use it in GitHub Desktop.
Save purdy/197a210480bcfe244d0b9277034d1b77 to your computer and use it in GitHub Desktop.
<?php
/**
* Quick utility script to send email out ... before you send this out,
* run this to load up the Sendgrid API key into your environment:
* source ./sendgrid.env
*
* Also, this code uses composer and the sendgrid/sendgrid library:
* composer require sendgrid/sendgrid
*/
require 'vendor/autoload.php';
$fh = fopen('contacts.csv', 'r');
$header = fgetcsv($fh);
$all_rows = [];
while ($row_data = fgetcsv($fh)) {
$row = array_combine($header, $row_data);
$all_rows[] = $row;
}
fclose($fh);
$chunks = array_chunk($all_rows, 1000);
$sent = $chunk_num = 0;
foreach ($chunks as $chunk) {
echo "Sending chunk #$chunk_num...\n";
$request_body = [
'from' => [
'email' => 'do-not-reply@example.com',
'name' => 'John Smith',
],
'template_id' => 'c89a108f-6175-e76e-c806-5f193b336dbc',
'subject' => 'SUBJECT LINE GOES HERE',
'reply_to' => [
'email' => 'me@example.com',
'name' => 'John Smith',
],
'categories' => [
'category_name',
],
'tracking_settings' => [
'ganalytics' => [
'enable' => TRUE,
'utm_source' => 'UTMSOURCE',
'utm_medium' => 'email',
'utm_campaign' => 'UTMCAMPAIGN',
],
],
// Uncomment below to just send the request and see if the data structure is legit.
// 'mail_settings' => [
// 'sandbox_mode' => [
// 'enable' => TRUE,
// ],
// ],
];
$personalizations = [];
foreach ($chunk as $row) {
$url = $row['login_url'];
$email = trim(strtolower($row['email']));
$personalization = [
'to' => [
['email' => $email],
],
'substitutions' => [
'-url-' => $url,
'-fname-' => $row['fname'],
],
];
$personalizations[] = $personalization;
$sent++;
}
$request_body['personalizations'] = $personalizations;
// print_r($request_body);
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());
$chunk_num++;
}
printf("All done - sent %s emails total.\n", number_format($sent));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment