Dynamically send MailChimp newsletter via PHP

Today, I am going to demonstrate how to dynamically create, manage and send MailChimp campaign to a List via PHP. You will also learn how to insert dynamic content in editable content area inside template before sending email newsletter.

In case you are looking to add subscriber to MailChimp List using API, here’s article for you: Subscribe users to MailChimp List using PHP.

For this tutorial, we are using MailChimp API v3 wrapper written by Drew McLellan for our purpose. It is Super-simple, minimum abstraction MailChimp API v3 wrapper.

Let’s start our adventure with MailChimp.

What do you need?

First of all, you need MailChimp API key. You need to find or generate API key. For this, you have go to MailChimp API keys page by clicking your profile name to expand the Account Panel, and choosing  Account >> Extras drop-down >> API key. From this page, you can copy existing key or create new key.

After having API key, you need to create a list or using existing one. Then add some subscribers to the list. We need ID of this List to send newsletter. To find the List ID, navigate to the Lists page, click the drop-down menu next to the list you want to work with, and then choose Settings. Scroll to find the unique List ID field. The string of letters and numbers is the list ID. 

Finally, we need to create a template. In order to create a template, navigate to Templates page and click the Create Template button. If you want to insert content dynamically in the template, select ‘Code Your Own’. To add editable content area in the template, add attributes like mc:edit=”body” in the container. Save the template and note down the Template ID.

Creating a new MailChimp campaign

You can create a new campaign using POST /campaigns API call. Here’s how to do it with PHP:

use \DrewM\MailChimp\MailChimp;

$MailChimp = new MailChimp($your_api_key);

// Create or Post new Campaign
$result = $MailChimp->post("campaigns", [
    'type' => 'regular',
    'recipients' => ['list_id' => $list_id],
    'settings' => ['subject_line' => $newsletter_subject_line,
           'reply_to' => $reply_to,
           'from_name' => $from_name
          ]
    ]);
  
$response = $MailChimp->getLastResponse();
$responseObj = json_decode($response['body']);	

Manage Campaign Content

After creating Campaign, you can add dynamic content to the campaign. To insert dynamic content, you should send GET request with template_id  and sections to be inserted as follows:
GET /campaigns/{campaign_id}/content

// Manage Campaign Content
$html = file_get_contents('url_of_dynamic_content');
$result = $MailChimp->put('campaigns/' . $responseObj->id . '/content', [
      'template' => ['id' => $template_id, 
        'sections' => ['body' => $html]
        ]
      ]);

Send Campaign

Finally, we send newsletter to the List by calling:
POST /campaigns/{campaign_id}/actions/send

// Send Campaign		
$result = $MailChimp->post('campaigns/' . $responseObj->id . '/actions/send');

In this way, you can send MailChimp newsletter using PHP. Isn’t is so simple ? 🙂

In upcoming days, I am going to share how to send newsletter using Amazon Simple Email Service (Amazon SES).

10 comments

  • Thank you for this great tutorial!
    I did get stuck in the “Manage Campaign Content” section:
    On line 2, where it says
    $html = file_get_contents(‘url_of_dynamic_content’);
    Where exactly do we get this url_of_dynamic_content?

    Regards.

    • thedebuggers

      Hi Daniel,

      You should specify path to your dynamic content to include in the template. url_of_dynamic_content is path to your file or script which generates content.

      • Hi, I tried with code but always get an error

        Array ( [type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/ [title] => Bad Request [status] => 400 [detail] => Your Campaign is not ready to send. [instance] => )

        I create a template like this

        Primary Heading
        Sample copy. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
        Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id
        pulvinar odio lorem non turpis.
        Subheading
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

        Then i put content like this

        $html = ‘asdasdasdasdasdasdasd’;
        $result = $MailChimp->put(‘campaigns/f9dd4607a8/content’, [
        ‘template’ => [‘id’ => ‘431381’,
        ‘sections’ => [‘body’ => $html]
        ]
        ]);

        But nothing is working…

  • stergios7

    I have opened issue
    https://github.com/drewm/mailchimp-api/issues/192

    I have done everything but content is not updating (I have added the tag). Any clue?

    • thedebuggers

      Hi! The snippets in this article are taken from working code base.

      Could you please confirm that the value of $html is not empty or you have added Title to the campaign ?

  • Hello!
    Thank you so much for your article, it’s very useful.

    However, i have an issue with this. On the part of editing content of campaign, like :

    $CI->mailchimp->put(‘campaigns/’ . $responseObj->id . ‘/content’, [
    ‘template’ => [
    ‘id’ => 3889,
    ‘sections’ => [‘body’ => ‘my body’]
    ]
    ]);

    My campaign is never edited, even if in my template i have only this :

    Use your own custom HTML

    I just receive this text without any changing. Would you have a suggestion for me?

    Thank you 🙂

  • Oops, my HTML doesn’t appear in last comment. I meant that in my template i have my tag with attribute mc:edit=”body” 🙂

  • George

    Answered on github issue. If anyone else is stuck with the same problem $template_id must be an integer if you set it as $template_id =’0101′ instead of $template_id =0101 then the api can’t hand the request as it sees the id as a string not an integer.

  • sehrish

    Hey How send an email mailchimp using php

Leave a Reply