我使用PHPmailer发送邮件。
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = 'some address';
$mail->FromName = 'some name';
$mail->Subject = 'some subject';
$mail->Body = $bodytext;
$mail->IsHTML(true);
$mail->AddAddress('some email');
// FILES
for($i = 0; $i < $length; $i++)
{
$filedata['name'] = $_FILES['userfile']['name'][$i];
$path = "somepath";
move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $path);
{
$stmt = $pdo->prepare("INSERT...");
$stmt->execute($filedata);
$mail->AddAttachment( $path, $filedata['name']);
}
}
$mail->Send();
问题是,有时(并非总是)附件不包含在电子邮件中,而是总是上载到服务器并添加到数据库中。
出什么问题了?可能是在addAttachment时刻move_uploaded_file还没有完成上传吗?
答案 0 :(得分:0)
您需要检查文件是否已正确上传,文件是否为空以及PHPMailer是否可以加载文件。
try {
for ($i = 0; $i < $length; $i++) {
if ((int)$_FILES['userfile']['size'][$i] === 0) {
throw new RuntimeException('Zero length file; may exceed allowed size.');
}
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$i]));
$filename = $_FILES['userfile']['name'][$i];
if (!move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $uploadfile)) {
throw new RuntimeException("Failed to move file $filename to $uploadfile");
}
if (!$mail->addAttachment($uploadfile, $filename)) {
throw new RuntimeException("Failed to attach file $filename");
}
//Everything is ok, so do whatever else you need to do, like store the record in the DB
}
} catch (RuntimeException $e) {
echo 'File upload failed:', htmlspecialchars($e->getMessage());
}