Skip to content

Instantly share code, notes, and snippets.

@narainsagar
Last active December 4, 2024 19:39
Show Gist options
  • Save narainsagar/2355204f7866c35dba856e55e4cacf6f to your computer and use it in GitHub Desktop.
Save narainsagar/2355204f7866c35dba856e55e4cacf6f to your computer and use it in GitHub Desktop.
How to Dynamically send a newsletter with MailChimp 3.0 via PHP
<?php
/**
* Reference Links:
* - https://mailchimp.com/help/find-your-list-id/
* - https://stackoverflow.com/a/48655086/5228251
* - https://thedebuggers.com/send-mailchimp-newsletter-via-php/
*/
// Include Mailchimp API 3.0
include_once('./mailchimp.php'); // copy from here: https://github.com/drewm/mailchimp-api/blob/master/src/MailChimp.php
use \DrewM\MailChimp\MailChimp;
/* SET THE VARIABLES HERE BELOW */
// Configure --------------------------------------
$api_key = "YOUR_API_KEY"; // see: https://mailchimp.com/help/about-api-keys/
$list_id = "your list id here"; // see: https://mailchimp.com/help/find-your-list-id/
$subject = "Hello, You've successfully subscribed to our Newsletter!";
$reply_to = "Your Company Email Address";
$from_name = "Your Company Name";
$template_id = 99999; // INTEGER
$template_html = '<p>Ayo whatup? THIS IS THE SAMPLE CONTENT BODY OF MY EMAIL MESSAGE.</p>';
// STOP Configuring -------------------------------
// Start create email campaign ->
$MailChimp = new MailChimp($api_key);
// Create or Post new Campaign
$result = $MailChimp->post("campaigns", [
'type' => 'regular',
'recipients' => [
'list_id' => $list_id
],
'settings' => [
'subject_line' => $subject,
'reply_to' => $reply_to,
'from_name' => $from_name
]
]);
$response = $MailChimp->getLastResponse();
$responseObj = json_decode($response['body']);
$campaign_id = $responseObj->id;
// Update Template content
// FYI: Make sure your template is labeled as "Code your own"
$result = $MailChimp->put('campaigns/' . $campaign_id . '/content', [
'template' => array(
'id' => (int)$template_id,
'sections' => array(
'html' => $template_html
)
)
]);
// Send Campaign
$result = $MailChimp->post('campaigns/' . $campaign_id . '/actions/send');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment