23 Giugno, 2014 | Di

Inviare email da Drupal con le API 2.0 di Mailchimp

Inviare email da Drupal con le API 2.0 di Mailchimp

Una delle funzionalità più richieste per un sito "social" è quella di mandare newsletter e comunicazioni agli utenti. Drupal fornisce una serie di moduli per queste attività, ma nessuno utilizza le nuove API 2.0 di Mailchimp (la versione 1.3 è deprecata). Inviare una campagna ad un gruppo di utenti è abbastanza semplice, tutto quello che serve sono l'oggetto del messaggio e il testo da inserire in un template di Mailchimp. Il grosso del problema è dovuto alla scarsa documentazione delle nuove API.

Le API di Mailchimp non permettono di creare una nuova lista da zero, per cui per inviare dinamicamente una newsletter ad un insieme di indirizzi email bisogna prima creare un nuovo segmento in una lista già esistente. Quindi inviare la campagna a quel segmento.

Vediamo come esempio una semplice funzione che invia una campagna ad uno specifico segmento.

/**
 * @param array $emails
 *   The list of addresses to send the newsletter to.
 * @param string $subject
 *   The newsletter subject
 * @param array $sections
 *   An array of sections that will be merged into template. Keys have to be
 *   equal to the template's sections in MailChimp. Remember that Mailchimp APIs
 *   does not support repeated sections in templates.
 */ 
function send($emails, $subject, $sections) {
  try {
    // 'mailchimp_api_key' contains the api key provided by MailChimp.
    $mailchimp = new Mailchimp(variable_get('mailchimp_api_key', ''));
    // Unique identifier for the newly created segment.
    $uuid = format_string("Newsletter @time", array('@time' => format_date(time(), 'custom', 'D, d/m/Y - H:i')));
 
    // Create the static segment, 'mailchimp_list' is the identifier
    // of a MailChimp list.
    $segment = $mailchimp->lists->staticSegmentAdd(
      variable_get('mailchimp_list', ''),
      $uuid
    );
 
    // Save the newly created segment id for later use.
    $segment = $segment['id'];
 
    for each ($emails as $email) {
      // Subscribe each email to MailChimp, if email already exists user data are updated.
      $result = $mailchimp->lists->subscribe(
        variable_get('mailchimp_list', ''), // The list to subscribe the user to.
        array('email' => $email),
        array(), // Merge vars, not used here.
        'html', // Email type.
        FALSE, // Double optin.
        TRUE, // Update existing.
        TRUE // Replace interests.
      );
 
      // Save internal MailChimp identifier for later use.
      $email = $result['email'];
      $euid = $result['euid'];
      $leid = $result['leid'];
 
      // Add the user to the static segment.
      $mailchimp->lists->staticSegmentMembersAdd(
        variable_get('mailchimp_list', ''),
        $segment,
        array(
          array(
            'email' => $email,
            'euid' => $euid,
            'leid' => $leid,
          )
        )
      );
    }
 
    // Create the campaign.
    $campaign = $mailchimp->campaigns->create(
      'regular', // Campaigns type.
      array(
        'list_id' => variable_get('mailchimp_list', ''),
        'subject' => $subject,
        'from_email' => variable_get('mailchimp_from_mail', ''),
        'from_name' => variable_get('mailchimp_from_name', ''),
        'template_id' => variable_get('mailchimp_template_id', ''),  // MailChimp template id.
        'auto_footer' => TRUE, // Lets MailChimp add a footer to the mail.
        'inline_css' => TRUE,
        'generate_text' => TRUE, // Auto generate plain-text version from HTML version.
      ),
      array(
        'sections' => $sections,
      ),
 
      // Segment campaign (send this newsletter only to the user of this segment).
      // Condition is an array of rules of matching, here we only match on the
      // 'static_segment' field.
      array(
        'match' => 'all',
        'conditions' => array(array('field' => 'static_segment', 'op' => 'eq', 'value' => $segment))
      )
    );
 
    // Send the campaign. Optionally you could remove this line and send the
    // campaign directly from MailChimp.   
    $mailchimp->campaigns->send($campaign['id']);
 
  } catch (Exception $e) {
    drupal_set_message(t('Unexpected exception (@error)', array('@error' => $e->getMessage())), 'error'); 
  }
}

Quindi per spedire la newsletter possiamo usare qualcosa come:

send(array('mail1@example.com', 'mail2@example.com'), 'This is the subject', array('mc_std_preheader_content' => 'Lorem ipsum', 'mc_std_content00' => 'Lorem ipsum'));

Per ulteriori informazioni, puoi leggere la documentazione delle API 2.0 di Mailchimp, mentre su BitBucket puoi trovare il wrapper PHP utilizzato in questo esempio.

In Wellnet abbiamo sviluppato diverse integrazioni che forniscono a Mailchimp, via API, utenti, contenuti ed altre entità di un sito Drupal, il tutto tramite complesse regole di selezione. Abbiamo così permesso ai nostri clienti di integrare due strumenti di marketing digitale molto potenti.

Potrebbe interessarti: