通过 PHP 将 Mailchimp 时事通讯发送到列表

Send Mailchimp newsletter to List via PHP

有没有办法将自己设计的 HTML 和 CSS 电子邮件从 .php 页面发送到 Mailchimp 列表?我想使用我自己的新闻稿模板将新闻稿功能集成到管理面板并从那里发送。

我不想每次发送电子邮件时都必须登录 Mailchimp,尤其是因为模板每次都相同。

是的,你可以。 MailChimp 的详细信息和示例可通过登录其控制面板获得。使用他们的表单域,设计您自己的表单。

<form action='http://xxxx.xxxxlist-manage.com/subscribe' method='post'>
    <p><input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="enter email address"></p>
    <p><input type="submit" value="Sign Up" name="subscribe" id="mc-embedded-subscribe" class="btn"></p>
    <input type='hidden' name='u' value='xxxxxxx'>
    <input type='hidden' name='id' value='xxxxxxx'>
</form>
MailChimp API 的

v2.0(已弃用)具有 Campaign Creation and Campaign Send 方法。这些不是最容易使用的方法,但当前的 API (v3.0) 还没有它们,所以这是你最好的选择。

如果您不想将模板上传到 Mailchimp 并通过点击他们的 API 发送活动,Mandrill(正如上面评论中提到的@Whymarrh)可能是一个不错的选择。

尽管它适用于交易电子邮件(欢迎、密码恢复等),但您可以通过 SMTP 一次向最多 1000 个用户发送邮件。另外,您可以在“集成”部分将您的 Mailchimp 帐户连接到您的 Mandrill 帐户,以跟踪收件人 activity。

我的建议是安装 Mandrill PHP API 客户端,将您的模板上传到 Mandrill,为您的用户列表点击 Mailchimp API,然后将其输入到山魈 send-template call that you trigger through your admin panel. (Pro tip on sending mass emails: Mandrill sending to multiple people as separate message via the REST API).

您的问题分为两部分:

  1. 如何从 MailChimp 中获取我的电子邮件列表?
  2. 如何向任意电子邮件地址发送电子邮件?

这里第一个块是最重要的。第二块有 可能的答案,应该很容易完成。


从 MailChimp 获取列表

MailChimp 提供了一个重要的 API。目前,他们正在开发 v3.0,但 v2.0 仍标记为 'current',因此我们将依赖 API 的那个版本。要使用 API, MailChimp recommends a few third-party packages. For this example, I am using mailchimp-api 可以使用 composer 安装:

$ composer require drewm/mailchimp-api

要向 MailChimp 验证您自己的身份,您需要一个 API 密钥MailChimp provides full instructions 获取 API 密钥,但简短版本是这样的:

  1. Click your profile name to expand the Account Panel, and choose Account.

  2. Click the Extras drop-down menu and choose API keys.

  3. Copy an existing API key or click the Create A Key button.

  4. Name your key descriptively, so you know what application uses that key.

接下来,您需要您的 列表 ID,用于您要从中获取电子邮件的列表。再次,MailChimp provides the best documentation。我的列表 ID 是一个包含字母和数字的 10 个字符的字符串。

最后,我们写PHP:

$apiKey = /*Your API key*/;
$listId = /*Your List ID*/;

$MailChimp = new \Drewm\MailChimp($apiKey);
$args = array(
    'id' => $listId,
);

$result = $MailChimp->call('lists/members', $args);

//Check for any errors first, if none have occured, build the email list.
if(isset($result['status']) && $result['status'] == 'error'){
    throw new Exception('call to Mailchimp API has failed.');
} else {
    $emails = array();
    //Build an array of emails for users that are currently subscribed. 
    foreach($result['data'] as $recipient){
        if($recipient['status'] == 'subscribed' && !empty($recipient['email'])){
            $emails[] = $recipient['email'];
        }
    }
}

$MailChimp->call('lists/members', $args) returns 一个非常重要的 JSON 响应,包含 很多 有趣的信息。如果您通过 MailChimp 中的合并设置存储个性化信息,它们将在此 JSON 响应中可用。但是,为了让这个示例尽可能简单,我只检查了用户是否订阅并存储了他们的电子邮件地址。

在此块的末尾,$emails 现在将所有电子邮件地址存储在您的列表中。由于这每次都会调用 API,因此在 MailChimp 上取消订阅您的邮件列表的任何人也将在此处被删除。

在此阶段可能会出现问题。如果你有一个大列表(我只测试了 4 个),你可能 运行 进入内存问题,其中 PHP 试图构建一个巨大的 $emails 数组。如果你 运行 遇到这个问题,你应该把阅读电子邮件分成更小的块,然后像这样发送电子邮件。


使用PHP

发送批量电子邮件

其他人建议使用 Mandrill 发送群发电子邮件。这是个坏主意。 Mandrill 是 MailChimp 的姊妹服务,旨在发送 transactional email - MailChimp 用于批量电子邮件(如时事通讯)。

有很多方法可以使用 PHP 发送电子邮件,我选择使用 Sendgrid as my SMTP provider and SwiftMailer to connect to it. Other alternatives would be to use PHP's mail() function or a different library like PHPMailer

您可以使用 Composer 安装 SwiftMailer:

$ composer require swiftmailer/swiftmailer @stable

我在 中详细介绍了 SwiftMailer 和 SMTP 服务(尽管上下文略有不同)。但是这个例子会做它需要做的事情。

$sendgridUser = /*SendGridUsername*/;
$sendgridPassword = /*SendGridPassword*/;

$subject = "Thank you for using MailChimp Lists!";
$fromAddress = "HPierce@example.com";
$fromName = "Hayden Pierce";
$body = file_get_contents(/*path to content (body.html)*/);
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587, 'tls')
  ->setUsername($sendgridUser)
  ->setPassword($sendgridPassword)
  ;

foreach($emails as $email){
    $mailer = Swift_Mailer::newInstance($transport);

    $message = Swift_Message::newInstance()
      ->setSubject($subject)
      ->setFrom(array($fromAddress => $fromName))
      ->setTo($email)
      ->setBody($body);

    $mailer->send($message);
    exit();
}

为简单起见,我从静态 HTML 文件中读取了整个正文。您可以考虑使用像 Twig 这样的模板引擎来更好地使用模板实现它。


所有这些代码放在一起看起来像这样:

//Loading in composer dependencies
require "vendor/autoload.php";

//Provided by Mailchimp account settings
$apiKey = /*MailChimp API keys*/;
$listId = /*MailChimp List id*/;

$sendgridUser = /*SendGridUser*/;
$sendgridPassword = /*SendGridPassword*/;

$subject = /*The subject line of your email*/;
$fromAddress = /*The email address for your FROM line*/;
$fromName = /*The name in your FROM line*/;
$body = file_get_contents(/*path to your html content*/);

$MailChimp = new \Drewm\MailChimp($apiKey);
$args = array(
    'id' => $listId,
);

$result = $MailChimp->call('lists/members', $args);

//Check for any errors first, if none have occurred, build the email list.
if(isset($result['status']) && $result['status'] == 'error'){
    throw new Exception('call to Mailchimp API has failed.');
} else {
    $emails = array();
    //Build an array of emails for users that are currently subscribed. 
    foreach($result['data'] as $recipient){
        if($recipient['status'] == 'subscribed' && !empty($recipient['email'])){
            $emails[] = $recipient['email'];
        }
    }
}

//Setup for sending emails to an arbitrary list of emails using Sendgrid.
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587, 'tls')
  ->setUsername($sendgridUser)
  ->setPassword($sendgridPassword)
  ;

foreach($emails as $email){
    //Send emails to each user.
    $mailer = Swift_Mailer::newInstance($transport);

    $message = Swift_Message::newInstance()
      ->setSubject($subject)
      ->setFrom(array($fromAddress => $fromName))
      ->setTo($email)
      ->setBody($body);

    $mailer->send($message);
}

创建带有自定义的广告系列HTML

使用campaigns/createapi端点:https://apidocs.mailchimp.com/api/2.0/campaigns/create.php

PHP 包装器在这里:https://bitbucket.org/mailchimp/mailchimp-api-php

看来Mailchimp_Campaigns::create是你可以使用的功能。密切关注 $content 参数(html string for raw/pasted HTML content)

创建活动后,您将获得它的 ID。

发送创建的活动

使用函数 Mailchimp_Campaigns::send 和之前创建的活动的 ID