【发布时间】:2014-11-17 23:10:18
【问题描述】:
我正在尝试通过电子邮件发送附件,但即使正确的文件保存在服务器中,附加到电子邮件的文件也是空的 (0 kb)。
我正在使用 gmail 发送电子邮件。
这是我的代码的相关部分:
if (empty($error)) {
//boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_randx";
//tell the headers about the boundary
$header .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"$mime_boundary\"";
//define the first part of the email, which is the text part
$message = "\r\n" . "--$mime_boundary\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\r\n" ;
//build the body of the 1st part of the email
$content_body = "
Email del formulario de contacto en ".home_url().": <br />
//whatever
";
$message .= $content_body . "\r\n";
$message .= "--$mime_boundary\n";
//define the second part of the email, which is the atachments
//if a file has been uploaded
if (!empty($_FILES['cv']['name'])){
// Open the file for a binary read
$file = fopen($temp_name,'rb');
// Read the file content into a variable
$data = fread($file,filesize($temp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
// Actually build the second part of the email
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
}
//send th email
mail( $receive_email, "Email del formulario de contacto en web", $message, $header);
$msg = $succesful_text;
}
我的猜测是我在这里做错了:
$message .= "Content-Type: \"application/octet-stream\";\r\n name=\"" . $file_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\r\n filename=\"" . $file . "\"\r\n\r\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "--$mime_boundary--\n";
但我不知道它会是什么。
我知道我可以使用库,但我想看看我的代码有什么问题,只是为了学习。
我们将不胜感激。
索尼娅
【问题讨论】:
-
查看消息的来源,你看到那里有base64编码的数据吗?从那里显示相应的标题。
-
我非常喜欢在双引号中嵌入变量,但您必须注意以下问题:
$mime_boundary = "==Multipart_Boundary_x$semi_randx";尝试使用大括号或连接运算符。此外,按照@Cheery 的建议粘贴您的消息文本。
标签: php email attachment