通过PHP发送邮件:如果附件为空,如何发送邮件?

时间:2015-08-02 17:30:29

标签: php forms validation wordpress

感谢wonderful tutorial by Agbonghama Collins,我已经开始使用WP插件供我个人使用,它可以输出一个带文件附件的简单联系表单。

目前,有两个文件附件字段,但它们不应该是必需的。但是,如果其中任何一个为空,则表单输出以下错误:

  

警告:FILE_GET_CONTENTS()[FUNCTION.FILE-GET-CONTENTS]:FILENAME不能空〜/ SP-FORM-EXAMPLE.PHP在线55

电子邮件最终发送,但无论如何都会收到两个附件,其中一个或两个都是空的,具体取决于上传到表单的内容。下图描绘了仅包含一个附件时的外观:

screenshot of "two attachments", when there should only be one

对于文件输入字段,我用这种方式调用变量......

    if ( isset( $_POST['cf-submitted'] ) ) {

            ...

            $first_attachment = chunk_split(base64_encode(file_get_contents($_FILES['cf-attachment']['tmp_name'])));
            $first_filename = $_FILES['cf-extra_attachment']['name'];
            $second_attachment = chunk_split(base64_encode(file_get_contents($_FILES['cf-attachment']['tmp_name'])));
            $second_filename = $_FILES['cf-extra_attachment']['name'];

            ...

...并将邮件作为MIME流传输。所以,我的问题是:有没有办法在处理和发送电子邮件时允许这些变量为空,这样在发送的电子邮件中将包含适当数量的附件,并且不会返回任何错误?代码示例会有所帮助:)

为了更清楚地参考,这是整个插件文件。它很轻,不使用帮助程序脚本。提前谢谢大家!!

    <?php
/*
Plugin Name: Contact Form Plugin
Plugin URI: http://dbudell.com
Description: Modification to the "Simple non-bloated WordPress Contact Form" by Agbonghama Collins (http://w3guy.com); now allows for file attachments.
Version: 1.0
Author: Daniel Bogre Udell (@dbudell)
Author URI: http://dbudell.com
*/

function html_form_code() {
    echo '<form enctype="multipart/form-data" action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
    echo '<p>';
    echo 'Your Name (required) <br/>';
    echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Your Email (required) <br/>';
    echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Subject (required) <br/>';
    echo '<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'File Attachment (required)';
    echo '<input type="file" name="cf-attachment" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Second File Attachment (required)';
    echo '<input type="file" name="cf-extra_attachment" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Your Message (required) <br/>';
    echo '<textarea rows="10" cols="35" name="cf-message">' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '</textarea>';
    echo '</p>';
    echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
    echo '</form>';
}

function deliver_mail() {

    // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {

        // collect form values
        $name = sanitize_text_field( $_POST['cf-name'] );
        $email   = sanitize_email( $_POST['cf-email'] );
        $subject = sanitize_text_field( $_POST['cf-subject'] );
        $message = esc_textarea( $_POST['cf-message'] );
        $first_attachment = chunk_split(base64_encode(file_get_contents($_FILES['cf-attachment']['tmp_name'])));
        $first_filename = $_FILES['cf-attachment']['name'];
        $second_attachment = chunk_split(base64_encode(file_get_contents($_FILES['cf-extra_attachment']['tmp_name'])));
        $second_filename = $_FILES['cf-extra_attachment']['name'];

        $boundary =md5(date('r', time())); 

        $to = get_option( 'admin_email' );

        $headers = "From: $name <$email>" . "\r\n";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message="This is a multi-part message in MIME format.

--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

--_2_$boundary
Content-Type: multipart/alternative; boundary=\"_3_$boundary\"

--_3_$boundary
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit

$message

--_3_$boundary--
--_2_$boundary
Content-Type: application/octet-stream; name=\"$first_filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$first_attachment
--_2_$boundary--

--_1_$boundary
Content-Type: application/octet-stream; name=\"$second_filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$second_attachment
--_1_$boundary--";

        // If email has been processed for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers ) ) {
            echo '<div>';
            echo '<p>Thanks for contacting me, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }
    }
}

function cf_shortcode() {
    ob_start();
    deliver_mail();
    html_form_code();

    return ob_get_clean();
}

add_shortcode( 'test_contact_form', 'cf_shortcode' );

?>

2 个答案:

答案 0 :(得分:0)

只需检查是否设置了额外的附件,如果没有,则跳过该部分:

if(isset($_FILES['cf-extra_attachment']['tmp_name'])) {
    $second_attachment = chunk_split(base64_encode(file_get_contents($_FILES['cf-extra_attachment']['tmp_name'])));
    $second_filename = $_FILES['cf-extra_attachment']['name'];
}

答案 1 :(得分:0)

使用wp_mail发送附件,试试这个

function deliver_mail() {

    // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {

        // collect form values
        $name = sanitize_text_field( $_POST['cf-name'] );
        $email   = sanitize_email( $_POST['cf-email'] );
        $subject = sanitize_text_field( $_POST['cf-subject'] );
        $message = esc_textarea( $_POST['cf-message'] );


        $attachements = array();

        if (isset($_FILES['cf-attachment']['tmp_name'])) {
            $attachements[] = $_FILES['cf-attachment']['tmp_name'];
        }

        if (isset($_FILES['cf-extra_attachment']['tmp_name'])) {
            $attachements[] = $_FILES['cf-extra_attachment']['tmp_name'];
        }


        $to = get_option( 'admin_email' );

        $headers = "From: $name <$email>" . "\r\n";

        // If email has been processed for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers, $attachements ) ) {
            echo '<div>';
            echo '<p>Thanks for contacting me, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }
    }
}

或设置附件名称的其他版本:

        add_action("phpmailer_init", function ($phpmailer) {

            if (isset($_FILES['cf-attachment']['tmp_name'])) {
                $phpmailer->addAttachment(
                    $_FILES['cf-attachment']['tmp_name']
                    , $_FILES['cf-attachment']['name']
                );
            }

            if (isset($_FILES['cf-extra_attachment']['tmp_name'])) {
                $phpmailer->addAttachment(
                    $_FILES['cf-extra_attachment']['tmp_name']
                    , $_FILES['cf-extra_attachment']['name']
                );
            }

        }, 10, 1);


        // If email has been processed for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers) ) {
            echo '<div>';
            echo '<p>Thanks for contacting me, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }