使用 PHPMailer 根据用户选中的复选框向用户发送附件?

Using PHPMailer to send attachments to the user based on the checkboxes they have checked?

我需要根据用户在表单中选择的复选框发送附件(这是请求手册,他们可以请求多个)。

我一直在阅读较早的问题,显然 PHPMailer 可以节省大量时间并减少附加文件的错误,因此我选择了该选项。这是我的代码:

表格:

<form method="post" action="form-confirm">
    Email: <input type="text" name="email" value="email"><br />
    Classic XL Parts: <input type="checkbox" name="document[]" value="ClassicXL" /><br />
    Racer 45 Parts: <input type="checkbox" name="document[]" value="Racing45" /><br />
    Flexer XL 45 Parts: <input type="checkbox" name="document[]" value="FlexerXL" /><br />
    <br />
    <input type="submit" value="Submit" />
</form>

PHP(我添加了评论来解释我需要做什么):

    require_once '/php/PHPMailer/class.phpmailer.php'; 

    $files = array(
        'ClassicXL' => '/manuals/classic-xl-parts.pdf',
        'Racing45' => '/manuals/racing-45-parts.pdf',
        'FlexerXL' => '/manuals/flexer-xl-parts.pdf'
    );

    $checkboxesChecked = array(
     // Do I need to have another array that stores the checkboxes ticked? 
    );

    if(isset($_POST) && ($_POST['submit'] == 1)) {
        $email = new PHPMailer();
        $email->From      = 'webmaster@admin.com';
        $email->FromName  = 'Webmaster';
        $email->Subject   = 'Here are the files you requested:';
        $email->addAddress($_POST['email']);
        // My idea here, is that for every $checkboxesChecked, check through the $files 
        // for the corresponding file and attach to the email
        for ( ) { 
            $file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
            $email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

            return $email->Send();
        }
    } else {
        return false;
    }

正如您从我的评论中看到的那样,我对如何完成任务有一个大致的了解,我只是需要一些帮助才能达到目标。

这应该是您需要的:

$email->addAddress($_POST['email']);
if (array_key_exists('document', $_POST)) {
    foreach ($_POST['document'] as $file) {
        if (array_key_exists($file, $files)) {
            $email->addAttachment($files[$file]);
        }
    }
}
//Don't send until you've attached everything
return $email->send();

其他一些位 - 在发送之前检查 addAddress 中的 return 值,以防收到无效地址;如果发送失败,您可能需要从 $email->ErrorInfo.

检索一些错误信息