Search code examples
drupal-7mailchimp

Drupal 7 create and send mailchimp campaign programmatically


How to create and send mailchimp campaign programmatically in drupal 7 ?


Solution

  • function kf_mailchimp_create_campaign() {
      if (!isset($_GET['cron_key']) || ($_GET['cron_key'] != 'kQ7kOy4uRgPJd1FX1QQAERPeSYuPjp1qBW65goYcbDQ')) {
        watchdog('kf_mailchimp', 'Invalid cron key !cron_key has been used to create campaign.', array('!cron_key' => $_GET['cron_key']));
        drupal_exit();
      }
    
      $data['site_url'] = url('<front>', array('absolute' => TRUE));
      $data['site_logo'] = theme_image(array(
        'path' => drupal_get_path('theme', 'knackforge') . '/logo.png',
        'alt' => 'KnackForge',
        'attributes' => array('border' => 0),
      ));
    
      $options = array(
        'list_id' =>  $mc_list_id, // Change this to match list id from mailchimp.com.
        'from_email' => variable_get('site_mail'),
        'from_name' => 'KnackForge',
        'to_email' => variable_get('site_name')
      );
    
      $type = 'regular';
      $q = mailchimp_get_api_object(); // Make sure a list has been created in your drupal site.
    
      $results = views_get_view_result('deal_mailchimp', 'page');
      // Check to prevent sending empty newsletter
      if (empty($results)) {
        watchdog('kf_mailchimp', 'No active deals to send for today');
        drupal_exit();
      }
    
      $data['deals'] = views_embed_view('deal_mailchimp', 'page');
    
      $content = array(
        'html' => theme('kf_mailchimp', $data),
      );
    
      $options['subject'] = t('Newsletter');
      $options['title'] = $options['subject'] . ' - ' . date('r');
      $options['tracking'] = array(
        'opens' => TRUE,
        'html_clicks' => TRUE,
        'text_clicks' => TRUE
      );
    
      $options['authenticate'] = false;
      $options['analytics'] = array('google'=>'atphga');
    
      $cid = $q->campaignCreate($type, $options, $content);
    
      watchdog('kf_mailchimp', 'Created campaign');
    
      $result = $q->campaignSendNow($cid);
    
      watchdog('kf_mailchimp', 'campaignSendNow() response !result', array('!result' => '<pre>' . print_r($result, 1) . '</pre>'));