我在 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.php
文件中,我有以下代码利用 PHPMailer()
发送电子邮件:
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_file
附加到电子邮件中并发送。我不关心在 process.php
脚本通过电子邮件发送文件后保存文件。
我知道我需要在某处添加 AddAttachment();
(我假设在 Body
行下)以便发送附件。但是……
- 我要在
process.php
文件的顶部放置什么以拉入文件uploaded_file
?喜欢使用$_FILES['uploaded_file']
从 contact-us.php 页面提取文件吗? AddAttachment();
中包含哪些内容,以便将文件附加到电子邮件中并随电子邮件一起发送?此代码需要放在哪里?
请帮忙提供代码!谢谢!
最佳答案
尝试:
if (isset($_FILES['uploaded_file'])
&& $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK
) {
$mail->addAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
可以找到附加多个文件上传的基本示例 here .
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'
)
关于php - 使用 phpMailer 和 PHP 从表单发送文件附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805058/