Using swiftmailer and sending attachments

后端 未结 1 779
[愿得一人]
[愿得一人] 2021-01-22 14:50

I am trying to modify a script to send a email with an attachment. It works right now but all the fields are required and I was wondering what I am missing to make it so the fie

相关标签:
1条回答
  • 2021-01-22 15:09

    you can remove the for each but then you'll have to request each posted field individually and process/validate them one at a time instead of in a loop as the loop is pulling all the post vars to local vars.

    Also you don't need to require the swift mailer includes etc inside of the loop they can be moved outside of the loop as can the $mailer = new transport start line that can all go outside of the loop

    EDIT WITH EXAMPLE

    if (isset($_POST)) { //BAD BAD BAD way of checking there's better ways
    
    $success = $error = false;
    
    $input1 = $_POST['input1'];
    $input2 = $_POST['input2'];
    $input3 = $_POST['input3'];
    $input4 = $_POST['input4'];
    
        $dir = dirname(__FILE__);
        // THIS BIT IS RETARDED BUT LEAVING IT IN FOR NOW
        ob_start();
        require_once($dir.'/html.php');
        $html_message = ob_get_contents();
        ob_end_clean();
        // END RETARDED BIT
        require_once($dir.'/swift/swift_required.php');
        $mailer = new Swift_Mailer(new Swift_MailTransport());
        if (isset($_FILES) && strlen($_FILES['attachment']['name']) > 0) { //here we're checking that there is attachments if there are then we're going to do the attach sw code
            $message = Swift_Message::newInstance()
                       ->setSubject('Imperial Order') // Message subject
                       ->setTo(array($input1 => $input2, 'ehilse@paifashion.com' => 'Janet McCauley')) // Array of people to send to
                       ->setFrom(array('noreply@paifashion.com' => 'Imperial Order'))
                       ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
                       ->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
        } else {
            //non attach sw code
            $message = Swift_Message::newInstance()
                       ->setSubject('Imperial Order') // Message subject
                       ->setTo(array($input1 => $input2, 'ehilse@paifashion.com' => 'Janet McCauley')) // Array of people to send to
                       ->setFrom(array('noreply@paifashion.com' => 'Imperial Order'))
                       ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
        }
        //there's better ways of doing the above but as an example this will suffice.
        // Send the email, and show user message
        if ($mailer->send($message)) {
            $success = true;
        } else {
            $error = true;
        }
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题