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

How to send an Encrypted Zip Archive as Mail Attachment in PHP?

我找到了有关加密 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>";