我使用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还没有完成上传?
发布于 2018-06-21 18:25:56
您需要检查文件是否正确上载,文件是否为空,以及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());
}
https://stackoverflow.com/questions/50962478
复制相似问题