我需要回复收到的电子邮件,包括其中包含的附件。 我编写了这段代码,但由于某些原因,当我检查调试日志和mandrill API日志时,附件并未包含在请求中。 哪里有我的错?
if ($message['attachments'])
{
$mail=
[
'html' => $mail->msg->html,
'text' => $mail->msg->text,
'subject' => $mail->msg->subject,
'from_email' => 'test@test.com',
'from_name' => $mail->msg->from_name,
'to' => [
[
'email' => 'test@test.com',
'name' => 'test@test.com',
'type' => 'to'
]
],
'headers' => [
'Reply-To' => $mail->msg->from_email
],
];
//just some sample data for testing
foreach ($message['attachment'] as $attachment)
{
$mail['attachments']['name'] ='sample.png';
$mail['attachments']['type'] ='image/png';
$mail['attachments']['content'] ='iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
}
$async = false;
$ip_pool = 'Main Pool';
$v = var_export( $mail, true);
file_put_contents('phplog.txt', 'gesendet: ' . $v, FILE_APPEND);
$result = $mandrill->messages->send($mail, $async, $ip_pool, $send_at);
}
答案 0 :(得分:2)
下面的行看起来很可疑。如果您在此处查看https://mandrillapp.com/api/docs/messages.html。您可以清楚地看到attachments
是一个多维数组。
//just some sample data for testing
foreach ($message['attachment'] as $attachment)
{
$mail['attachments']['name'] ='sample.png';
$mail['attachments']['type'] ='image/png';
$mail['attachments']['content'] ='iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
}
至少应该如下,但您仍然不能在代码中使用$attachment
。但正确的用法如下。
foreach ($message['attachment'] as $key => $attachment)
{
$mail['attachments'][$key]['name'] ='sample.png';
$mail['attachments'][$key]['type'] ='image/png';
$mail['attachments'][$key]['content'] ='iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
}
如果您想以更清晰的方式尝试,请使用以下内容:
$attachment = [];
$attachment['name'] ='sample.png';
$attachment['type'] ='image/png';
$attachment['content'] ='iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$mail['attachments'][] = $attachment;
根据评论更新:
事情看起来很好,只需将if语句if ($message['attachments'])
更改为if (is_array($message['attachments']) && count($message['attachments']) > 1)
,然后将if语句$message['attachments'] = array_values($message['attachments']);
如下所示循环。只需注意$attachment
我添加到语义键,你可以根据自己的需要进行更改。我不知道你获取文件,静态或文件上传的来源在哪里。我作为一个例子添加了。
foreach ($message['attachment'] as $key => $attachment)
{
$mail['attachments'][$key]['name'] =$attachment['fileName'];
$mail['attachments'][$key]['type'] =$attachment['mimeType'];
$mail['attachments'][$key]['content'] = chunk_split(base64_encode(file_get_contents($attachment['filePath']))); ;
}