【问题标题】:Add multiple user-selected attachments to email将多个用户选择的附件添加到电子邮件
【发布时间】:2012-10-11 08:51:25
【问题描述】:

我正在为我的站点上的管理员实施基本的电子邮件功能。他们可以设置主题、内容等,然后将邮件发送给指定的收件人。我遇到的问题是附件。他们应该能够选择多个文件已经在网络服务器上(例如public_html/fileuploads/myfile.pdf)。

如果不能从网络服务器附加,那么我至少需要实现一种方法,他们可以从他们的 PC 附加多个文件。目前我正在使用 Swiftmailer,它接受这样的附件:

$message->attach(Swift_Attachment::fromPath('/path/to/file.pdf'));

所以我需要用户能够选择多个文件。我可以做到这一点:

<input type="file" name="attachment[]" multiple/>

但现在我不知道如何获取每个选定文件的完整路径,然后将每个文件添加为附件。它应该从 HTML 提交到我的 mailer.php 页面。

任何帮助将不胜感激。

【问题讨论】:

  • 我不是 100% 确定,但如果我没记错的话,如果您访问 PHP 脚本上的文件流,则不必将其保存到您的服务器(关于文件上传)
  • 您的问题到底是什么?如何处理文件上传,或者如何让用户从服务器选择文件以在附件中使用?这两个故事情节在您的帖子中交织在一起。你能澄清一下吗?
  • 好的,所以我想我需要的是如何获取用户在文件上传对话框中选择的所有文件的完整路径。

标签: php html


【解决方案1】:
// first get a list of the attachments
$attachments_dir = 'public_html/fileuploads';
$attachments = glob("$attachments_dir/*.pdf");

// then put them into the form
foreach ($attachments as $attachment) {
  echo '<input type="checkbox" name="attachments[]" value="',$attachment], '">',$attachment,'<br />'; 
 }


// then when the form is submitted, use them
$selected_attachments = $_POST['attachments'];
foreach ($selected_attachments as $attachment) {
  $message->attach(Swift_Attachment::fromPath($attachment));
}

请记住,虽然这表明您要执行的过程不是很安全。 例如,有人可以将附件更改为 /root/secretpasswords.txt,您可以附加一些意想不到的内容。

如果所有附件都在一个目录中,您可以只使用文件名部分而不是提交表单中的路径/文件名,但这应该足以让您开始。

【讨论】:

  • 非常感谢。正是我想要的。
【解决方案2】:

您将在 php 中获得文件名和 tmp 文件源,如下所示

for($i=0;$i<count($_FILES["attachment"]["name"]);$i++)  
{  
  if($_FILES["attachment"]["name"][$i] != "")  
  {  
    //here you will get all files selected by user.
    echo $_FILES["attachment"]["tmp_name"][$i];
    echo $_FILES["attachment"]["name"][$i] 

    //here you can copy files to your server, then pass one to your swift mailer function.
    //to copy file to your server, you can use copy() or move_upload_file() function.
  }  
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多