Simple función php para enviar un correo electrónico con Mandrill


¿Cuál es la forma más fácil de enviar un correo electrónico a través del servicio Mandrill de Mailchimp (utilizando la API)?

Aquí está el método de envío: https://mandrillapp.com/api/docs/messages.html#method=send

Aquí está el envoltorio de la API: https://bitbucket.org/mailchimp/mandrill-api-php/src/fe07e22a703314a51f1ab0804018ed32286a9504/src?at=master

Pero no puedo averiguar cómo hacer una función PHP que envíe y envíe por correo electrónico a través de Mandrill.

Alguien Puede ayudar?

Author: Toby Allen, 2013-01-23

5 answers

También tenemos un envoltorio de API oficial para PHP, que está disponible en Bitbucket o a través de Packagist, que envuelve la API Mandrill para usted.

Si su clave API Mandrill se almacena como una variable de entorno, aquí hay un ejemplo simple de envío usando una plantilla, con algunas variables de combinación y metadatos:

<?php
require 'Mandrill.php';

$mandrill = new Mandrill(); 

// If are not using environment variables to specific your API key, use:
// $mandrill = new Mandrill("YOUR_API_KEY")

$message = array(
    'subject' => 'Test message',
    'from_email' => '[email protected]',
    'html' => '<p>this is a test message with Mandrill\'s PHP wrapper!.</p>',
    'to' => array(array('email' => '[email protected]', 'name' => 'Recipient 1')),
    'merge_vars' => array(array(
        'rcpt' => '[email protected]',
        'vars' =>
        array(
            array(
                'name' => 'FIRSTNAME',
                'content' => 'Recipient 1 first name'),
            array(
                'name' => 'LASTNAME',
                'content' => 'Last name')
    ))));

$template_name = 'Stationary';

$template_content = array(
    array(
        'name' => 'main',
        'content' => 'Hi *|FIRSTNAME|* *|LASTNAME|*, thanks for signing up.'),
    array(
        'name' => 'footer',
        'content' => 'Copyright 2012.')

);

print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));

?>
 61
Author: Kaitlin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-11 20:55:25

Mandrill toma las solicitudes HTTP POST para todos sus métodos API y toma tu entrada como una cadena JSON. Este es un ejemplo básico de cómo enviar un correo electrónico. Utiliza cURL para hacer la petición HTTP:

$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';

$postString = '{
"key": "YOUR KEY HERE",
"message": {
    "html": "this is the emails html content",
    "text": "this is the emails text content",
    "subject": "this is the subject",
    "from_email": "[email protected]",
    "from_name": "John",
    "to": [
        {
            "email": "[email protected]",
            "name": "Bob"
        }
    ],
    "headers": {

    },
    "track_opens": true,
    "track_clicks": true,
    "auto_text": true,
    "url_strip_qs": true,
    "preserve_recipients": true,

    "merge": true,
    "global_merge_vars": [

    ],
    "merge_vars": [

    ],
    "tags": [

    ],
    "google_analytics_domains": [

    ],
    "google_analytics_campaign": "...",
    "metadata": [

    ],
    "recipient_metadata": [

    ],
    "attachments": [

    ]
},
"async": false
}';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);

$result = curl_exec($ch);

echo $result;
 22
Author: MrCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-23 07:45:41
// Simply Send Email Via Mandrill...

require_once 'Mandrill.php';
$mandrill = new Mandrill($apikey);

$message = new stdClass();
$message->html = "html message";
$message->text = "text body";
$message->subject = "email subject";
$message->from_email = "[email protected]";
$message->from_name  = "From Name";
$message->to = array(array("email" => "[email protected]"));
$message->track_opens = true;

$response = $mandrill->messages->send($message);
 5
Author: Muddasir Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-17 18:01:32

Esta es la pieza de código más básica que podría darte, solo lo craft hace segundos para un cliente y está funcionando sin problemas.

require_once 'path/to/your/mandrill/file/Mandrill.php';
 try {
    $mandrill = new Mandrill('your-API-key');
    $message = array(
        'html' => $htmlMessage,
        'subject' => $subject,
        'from_email' => $fromEmail,
        'from_name' => $fromName,
        'to' => array(
            array(
                'email' => $toEmail,
                'name' =>  $toName,
                'type' => 'to'
            )
        )
    );
    $result = $mandrill->messages->send($message);
    print_r($result);
} catch(Mandrill_Error $e) {
    echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
    throw $e;
}

También verifique su método de envío para obtener más opciones como encabezados, metadatos, archivos adjuntos, etc. https://mandrillapp.com/api/docs/messages.php.html#method-send

 2
Author: 0x1ad2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-12 17:20:42

Incluye la API de PHP: https://bitbucket.org/mailchimp/mandrill-api-php

Código: https://mandrillapp.com/api/docs/messages.php.html#method-send

Puede usar la carga automática de ZF para incluir la clase wrapper o Composer: https://mandrillapp.com/api/docs/index.php.html

 1
Author: octavian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-20 17:40:38