【问题标题】:Send email with template (Mandrill PHP)使用模板发送电子邮件 (Mandrill PHP)
【发布时间】:2013-06-22 11:19:06
【问题描述】:

我在 Mandrill 中创建了一个模板,但我不知道如何使用它来发送电子邮件。

下面是一个如何使用简单 html 的示例:

<?php

include_once "swift_required.php";

$subject = 'Hello from Mandrill, PHP!';
$from = array('you@yourdomain.com' =>'Your Name');
$to = array(
 'recipient1@example.com'  => 'Recipient1 Name',
 'recipient2@example2.com' => 'Recipient2 Name'
);

$text = "Mandrill speaks plaintext";
$html = "<em>Mandrill speaks <strong>HTML</strong></em>";

$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername('MANDRILL_USERNAME');
$transport->setPassword('MANDRILL_PASSWORD');
$swift = Swift_Mailer::newInstance($transport);

$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');

if ($recipients = $swift->send($message, $failures))
{
 echo 'Message successfully sent!';
} else {
 echo "There was an error:\n";
 print_r($failures);
}

?>

【问题讨论】:

    标签: php templates mandrill


    【解决方案1】:

    您可以使用Mandrill PHP API wrapper 发送电子邮件并使用模板。

    require 'Mandrill.php';
    
    $mandrill = new Mandrill('YOUR_API_KEY');
    
    $message = array(
        'subject' => 'My subject',
        'from_email' => 'marc@example.com',
        'to' => array(array('email' => 'recipient1@example.com', 'name' => 'Marc')),
        'merge_vars' => array(array(
            'rcpt' => 'recipient1@example.com',
            'vars' =>
            array(
                array(
                    'name' => 'FIRSTNAME',
                    'content' => 'Recipient 1 first name'),
                array(
                    'name' => 'LASTNAME',
                    'content' => 'Last name')
        ))));
    
    $template_name = 'YOUR-TEMPLATE-NAME';
    
    $template_content = array(
        array(
            'name' => 'main',
            'content' => 'Hi *|FIRSTNAME|* *|LASTNAME|*, thanks for signing up.'),
        array(
            'name' => 'footer',
            'content' => 'Copyright 2013.')
    
    );
    
    $response = $mandrill->messages->sendTemplate($template_name, $template_content, $message);
    print_r($response);
    

    如果你想通过 SwiftMailer 使用 SMTP,你可以调用 Render API 方法来渲染一个模板,这将为你提供完整的 HTML,你可以将它传递给 SwiftMailer,但这似乎有点冗长与 PHP API 包装器相比。

    【讨论】:

    • 谢谢,它的工作,只是一个更正:$mandrill = new Mandrill('YOUR_API_KEY');
    • 更多信息,我在 html 模板和 merge_vars 中设置了 |pspReference| 我使用了:'name' => 'pspReference', 'content' => 'Hello world'),但它不会改变值,你知道为什么吗?谢谢
    • 我收到此响应 { 状态:0,消息:“API 调用消息/发送模板失败:SSL 证书问题:无法获取本地颁发者证书”}
    • @HiteshModha,这个问题是因为您的网站需要在 SLL 证书 (HTTPS) 下。
    猜你喜欢
    • 2015-08-30
    • 2013-11-26
    • 2014-05-04
    • 2015-05-09
    • 2013-07-31
    • 2016-08-13
    • 1970-01-01
    • 2013-10-13
    相关资源
    最近更新 更多