沃梦达 / 编程问答 / php问题 / 正文

使用 phpMailer 和 PHP 从表单发送文件附件

Send File Attachment from Form Using phpMailer and PHP(使用 phpMailer 和 PHP 从表单发送文件附件)

本文介绍了使用 phpMailer 和 PHP 从表单发送文件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form on example.com/contact-us.php that looks like this (simplified):

<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() 发送电子邮件:

In my process.php file, I have the following code utilizing PHPMailer() to send an email:

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的附件.

The email sends the body correctly, but without the Attachment of uploaded_file.

我的问题

我需要将表单中的文件 uploaded_file 附加到电子邮件中并发送.在 process.php 脚本通过电子邮件发送文件后,我不关心保存文件.

I need the file uploaded_file from the form to be attached to the email, and sent. I do NOT care about saving the file after the process.php script sends it in an email.

我知道我需要在某处(我假设在 Body 行下)添加 AddAttachment(); 以发送附件.但是...

I understand that I need to add AddAttachment(); somewhere (I'm assuming under the Body line) for the attachment to be sent. But...

  1. 我在 process.php 文件的顶部放了什么来拉入文件 uploaded_file?喜欢使用 $_FILES['uploaded_file'] 从 contact-us.php 页面中提取文件吗?
  2. AddAttachment(); 的内容是什么来附加文件并与电子邮件一起发送?此代码需要放在何处?
  1. What do I put at the top of the process.php file to pull in the file uploaded_file? Like something using $_FILES['uploaded_file'] to pull in the file from the contact-us.php page?
  2. What goes inside of AddAttachment(); for the file to be attached and sent along with the email and where does this code need to go?

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

Please help and provide code!Thanks!

推荐答案

尝试:

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

也可以在此处找到基本示例.

Basic example can also be found here.

AddAttachment 的函数定义是:

public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

这篇关于使用 phpMailer 和 PHP 从表单发送文件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 phpMailer 和 PHP 从表单发送文件附件

基础教程推荐