Reputation: 802
I found answers on encrypting zip files and also on how to send files in mail attachments. Both in separate questions. So I combined the both to make it easier for others. This is a self answered question.
You will be able to generate a random unique password for each receiver and send the password along with the attachment in the mail.
Upvotes: 3
Views: 1663
Reputation: 802
Note : Most Servers will mark the attachment as unsafe as they wont be able to scan the zip archive for malicious files.
Following is the Code to send an Encrypted Zip Archive as mail attachment in PHP.
<?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>";
Upvotes: 3