使用phpMailer和PHP从表单发送文件附件无法从客户端 PC 附加文件(上载)

我有一个看起来像这样的表单(简化):example.com/contact-us.php

<form method="post" action="process.php" enctype="multipart/form-data">
  <input type="file" name="uploaded_file" id="uploaded_file" />
  <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
</form>

在我的文件中,我有以下代码用于发送电子邮件:process.phpPHPMailer()

require("phpmailer.php");

$mail = new PHPMailer();

$mail->From     = me@example.com;
$mail->FromName = My name;
$mail->AddAddress(me@example.com,"John Doe");

$mail->WordWrap = 50;
$mail->IsHTML(true);

$mail->Subject  =  "Contact Form Submitted";
$mail->Body     =  "This is the body of the message.";

电子邮件正确发送正文,但没有 附件。uploaded_file

我的问题

我需要将表单中的文件附加到电子邮件中并发送。我不在乎在脚本通过电子邮件发送文件后保存文件。uploaded_fileprocess.php

我知道我需要添加某个地方(我假设在行下面)才能发送附件。但是......AddAttachment();Body

  1. 我应该在文件顶部放置什么来拉入文件?喜欢使用的东西从联系我们.php页面中提取文件?process.phpuploaded_file$_FILES['uploaded_file']
  2. 要将文件与电子邮件一起附加和发送的内部内容是什么,以及此代码需要去哪里?AddAttachment();

请帮助并提供代码!谢谢!


答案 1

尝试:

if (isset($_FILES['uploaded_file'])
    && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK
) {
    $mail->addAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

可以在此处找到附加多个文件上传的基本示例。

的函数定义是:addAttachment

/**
 * Add an attachment from a path on the filesystem.
 * Never use a user-supplied path to a file!
 * Returns false if the file could not be found or read.
 * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
 * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
 *
 * @param string $path        Path to the attachment
 * @param string $name        Overrides the attachment name
 * @param string $encoding    File encoding (see $Encoding)
 * @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
 * @param string $disposition Disposition to use
 *
 * @throws Exception
 *
 * @return bool
 */
public function addAttachment(
    $path,
    $name = '',
    $encoding = self::ENCODING_BASE64,
    $type = '',
    $disposition = 'attachment'
)

答案 2

无法从客户端 PC 附加文件(上载)

在HTML表单中,我没有添加以下行,因此没有附件:

enctype=“multipart/form-data”

在形式上添加上面的行(如下所示)后,附件变得完美。

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

推荐