我已经尝试了一段时间来解决这个问题,我不知道。我正在尝试编写一个简单的表单来发送带有上传文件的电子邮件(最终将扩展为实际有用的东西),它根本就不起作用。
电子邮件是通过适当的正文传递的,但不包含任何附件。我已经尝试使用文件上传表单,AddAttachments链接到服务器上的文件,AddAttachments指向imgur上的图像,但没有一个工作;附件永远不会通过。我现在已经忍耐了,有没有人知道我做错了什么或没有phpmailer这样做的方法?
HTML表单
<form action="xxxx.php" id="upload" method="post" name="upload">
<input id="fileToUpload" name="fileToUpload" type="file" />
<input type="submit" />
</form>
PHP代码
require("../../../classes/class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "xx@xx.co.uk";
$mail->FromName = "Uploader";
$mail->AddAddress("xx@xx.co.uk");
$mail->Subject = "First PHPMailer Message";
$mail->Body = "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap = 50;
$mail->AddAttachment( $_FILES['fileToUpload']['tmp_name'], $_FILES['fileToUpload']['name'] );
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
答案 0 :(得分:0)
查看表单,您的表单标记中没有设置enctype =“multipart / form-data”。
此外,您需要进行文件附件检查,以确保在发送电子邮件之前实际附加。例如,
if (isset($_FILES['uploaded_file']) &&
$_FILES['fileToUpload']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['fileToUpload']['tmp_name'],
$_FILES['fileToUpload']['name']);
}
答案 1 :(得分:0)
您正在使用一些旧示例和旧版本的PHPMailer,因此我建议您update to the latest。您还需要了解how to handle file uploads,这是您所缺少的。这是the example bundled with PHPMailer:
<?php
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from@example.com', 'First Last');
$mail->addAddress('whoto@example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
$mail->msgHTML("My message body");
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'My uploaded file');
if (!$mail->send()) {
$msg = "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg = "Message sent!";
}
} else {
$msg = 'Failed to move file to ' . $uploadfile;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>