【问题标题】:Symfony2, Swiftmailer, Mandrill get responseSymfony2、Swiftmailer、Mandrill 得到响应
【发布时间】:2023-03-05 22:54:01
【问题描述】:

我们使用 Swiftmailer 和 Mandrill 构建了一个电子邮件系统。它工作得非常好,但现在我们想集成 webhook 以触发反弹/失败/...

此时,我们为发送的每封电子邮件添加一个带有唯一 ID 的自定义标头,并在 webhook 触发时找到返回的路。

它运行良好,但 mandrill 已经使用了我们可以使用的 _id,因此我们不会在其上添加“另一个”唯一 ID。

Mandrill 的回应如下:

[
    {
        "email": "recipient.email@example.com",
        "status": "sent",
        "reject_reason": "hard-bounce",
        "_id": "abc123abc123abc123abc123abc123"
    }
]

在 Swiftmailer 中是否有任何方法可以将此响应返回到 Symfony 中? (以便我们可以读取并存储 _id 供以后使用)

我知道我们可以使用 Mandrill php SDK,但最好还是继续使用 Swiftmailer。

编辑 正如here 解释的那样,我们正在使用带有基本 Swiftmailer 实例的 SMTP 传输。

<?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);
}

?>

【问题讨论】:

  • 您应该提及您使用 Mandrill 从 swiftmailer 发送消息的内容,因为答案可能就在该包中的某个地方。

标签: symfony swiftmailer mandrill


【解决方案1】:

我认为 Mandrill 不支持通过 SMTP 传递此回复,您必须为此使用 API。

例如,在accord/mandrill-swiftmailer 中有一个从 Mandrill 返回响应的方法:https://github.com/AccordGroup/MandrillSwiftMailer/blob/master/SwiftMailer/MandrillTransport.php#L215

您可以使用以下代码获取 Mandrill 的响应:

$transport = new MandrillTransport($dispatcher);
$transport->setApiKey('ABCDEFG12345');
$transport->setAsync(true); # Optional
$response = $transport->getMandrillMessage($message);
// $response now contains array with Mandrill's response.

您可以使用 accord/mandrill-swiftmailer-bundle 将其与 Symfonu 集成,之后您可以执行以下操作:

$response = $mailer->getTransport()->getMandrillMessage($message); 

【讨论】: