4

我正在尝试从 PHP 发送带有附件的加密电子邮件,但是,我的电子邮件只是在电子邮件客户端(在本例中为 MS Outlook)中显示为纯文本。这是我用来发送电子邮件的代码:

$semi_rand = md5(time());   
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";   
$fileatt = "\path\to\attachment";
$headers = array();
$headers['From'] = $email_from;
$headers['Subject'] = $email_subject; 
$headers['MIME-Version'] = "1.0";
$headers['Content-Type'] = "multipart/mixed; boundary=\"{$mime_boundary}\"";    

$file = fopen($fileatt,'rb');   
$data = fread($file,filesize($fileatt));
$data = chunk_split(base64_encode($data));     
fclose($file);   

//message part
$email_message = "This is a multi-part message in MIME format.\n\n" .   
                "--{$mime_boundary}\n" .   
                "Content-Type:text/html; charset=\"UTF-8\"\n" .   
                "Content-Transfer-Encoding: 7bit\n\n
                                     Please find the file attached\n\n";   


//file part
$email_message .= "--{$mime_boundary}\n" .   
                  "Content-Type: {$fileatt_type};\n" .   
                  " name=\"{$fileatt_name}\"\n" .   
                  "Content-Transfer-Encoding: base64\n\n" .   
                 $data . "\n\n" .   
                  "--{$mime_boundary}--\n";   

$mfile = fopen("msg.txt", "w");
fwrite($mfile, $email_message);
fclose($mfile);


$key = file_get_contents("mailcert.cer");

$encrypt = openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key, $headers);
if($encrypt){
    $data = file_get_contents("enc.txt");
    $parts = explode("\n\n", $data, 2);

    // Send mail
    $ok = mail($email_to, $email_subject, $parts[1], $parts[0]);
}  

该脚本有效,电子邮件已发送,并且可以在 Outlook 中对其进行解密,但是,结果如下所示:

--==Multipart_Boundary_x6434b5a09f1f49c571a633802cd36772x

Content-Type:text/html; charset="UTF-8"
Content-Transfer-Encoding: 7bit

Please find the file attached

--==Multipart_Boundary_x6434b5a09f1f49c571a633802cd36772x
Content-Type: application/octet-stream;
 name="1327490599scrippie.txt"
Content-Transfer-Encoding: base64

JG9sZElwID0gIjE5NS40Ni4zOS43MyINCiRuZXdJcCA9ICIqIg0KDQojIEdldCBhbGwgb2JqZWN0
cyBhdCBJSVM6Ly9Mb2NhbGhvc3QvVzNTVkMNCiRpaXNPYmplY3RzID0gbmV3LW9iamVjdCBgDQog
ICAgU3lzdGVtLkRpcmVjdG9yeVNlcnZpY2VzLkRpcmVjdG9yeUVudHJ5KCJJSVM6Ly9Mb2NhbGhv
[etc....]

--==Multipart_Boundary_x6434b5a09f1f49c571a633802cd36772x--

还有另一种发送带有附件的加密电子邮件的方法吗?或者有解决这个问题的方法吗?

4

1 回答 1

4

此问题的解决方案是将原始消息的标头包含在包含该消息的文件中。

在将文件写入磁盘之前,我添加了类似的内容:

foreach($headers as $headerkey => $headerval){
    $email_message = $headerkey . ": " . $headerval . "\r\n" . $email_message;
}

然后,从数组中删除 MIME-version 和 Content-Type 标头,然后再将其传递给openssl_pkcs7_encrypt()函数。

于 2012-01-26T10:36:47.080 回答