php - 如何在 PHP 中将加密的 Zip 存档作为邮件附件发送?

标签 php email-attachments ziparchive

我找到了有关加密 zip 文件以及如何在邮件附件中发送文件的答案。两者在不同的问题中。所以我把两者结合起来,让其他人更容易。这是一个自我回答的问题。

您将能够为每个接收者生成一个随机的唯一密码,并将密码与邮件中的附件一起发送。

最佳答案

注意:大多数服务器会将附件标记为不安全,因为它们将无法扫描 zip 存档中的恶意文件。

以下是在 PHP 中将加密的 Zip 存档作为邮件附件发送的代码。

<?php

$file_key="password"; //Password for the Zip Archive

$receiver_name = "Receiver Name";
$receiver_email = "Receiver Email";

$sender_name = "Sender Name";
$sender_mail = "Sender Mail";

//Main Content
$main_subject = "Mail Subject";
$main_body = "Mail Body";

echo "Creating Zip Archive <br>";
$zip = new ZipArchive();
$filename = "final-level.zip";   //Zip File Name
if ($zip->open($filename, ZipArchive::CREATE)===TRUE) {
    $zip->setPassword($file_key);
    $zip->addFile(
        "./dir/test.txt", //File Directory
        "test.txt" //New File Name inside Zip Archive
    );
    $zip->setEncryptionName('text.txt', //New File Name
    ZipArchive::EM_AES_256); //Encryption 
    $zip->close();
}else{
    echo "Cannot open Zip file <br>";
    exit("cannot open <$filename>\n");
}
echo "Created Zip File <br>";
//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
$file = chunk_split(base64_encode(file_get_contents($filename)));
$uid = md5(uniqid(time()));
//Sending mail to Server
$retval = mail($receiver_email, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n$main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");

//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################
//Output
if ($retval == true) {
    echo "Message sent successfully...";
} else {
    echo "Error<br>";
    echo "Message could not be sent...Try again later";
}
//Delete File from Server
if (file_exists($filename)) {
    unlink($filename);
}
echo "Unlinked File from Server <br>";
echo "Done <br>";

关于php - 如何在 PHP 中将加密的 Zip 存档作为邮件附件发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61653014/

相关文章:

php按预定义的顺序对数组进行排序

PHP 意外的 elseif

php - 动态生成的查询

php - 动态创建 PDF 并通过电子邮件发送

php - ZipArchive 无法打开文件 - 错误代码 : 19

php - 如何从 laravel mongodb 的结果集中删除主键?

android - 如何在电子邮件正文中添加图像

c# - 我可以发送图像和 rar 文件,但这些文件已被 asp.net 损坏?

php - ZipArchive() 向存档添加空字节的奇怪行为

php - Laravel 5 zip存档到存储与公开