简体   繁体   English

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

[英]Sending mail via PHP: How to send mail if attachment is empty?

Thanks to a wonderful tutorial by Agbonghama Collins , I've begun working on a WP plugin for my personal use, one that outputs a simple contact form with file attachments.多亏了Agbonghama Collins精彩教程,我已经开始开发一个供我个人使用的 WP 插件,它输出一个带有文件附件的简单联系表格。

As for now, there are two file attachment fields, but they shouldn't be mandatory.目前,有两个文件附件字段,但它们不应该是强制性的。 However if either is left empty, the form outputs the following error:但是,如果其中一个为空,则表单会输出以下错误:

WARNING: FILE_GET_CONTENTS() [FUNCTION.FILE-GET-CONTENTS]: FILENAME CANNOT BE EMPTY IN ~/SP-FORM-EXAMPLE.PHP ON LINE 55警告:FILE_GET_CONTENTS() [FUNCTION.FILE-GET-CONTENTS]:第 55 行 ~/SP-FORM-EXAMPLE.PHP 中的文件名不能为空

The email ultimately does send, but arrives with two attachments anyway, either one or both of which is empty, depending on what was uploaded to the form.电子邮件最终确实发送了,但无论如何都会带着两个附件到达,其中一个或两个都是空的,具体取决于上传到表单的内容。 The following image depicts what it looks like if only one attachment was included:下图描绘了如果只包含一个附件的情况:

“两个附件”的截图,应该只有一个

For the file input fields, I'm calling the variable this way...对于文件输入字段,我以这种方式调用变量...

    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'];

            ...

... and transmitting the mail as a MIME stream. ...并将邮件作为 MIME 流传输。 So, my question is this: is there any way to allow these variables to be empty when the email is processed and sent, such that the appropriate number of attachments would be included in the sent the email and no error would be returned?所以,我的问题是:有没有办法在处理和发送电子邮件时允许这些变量为空,以便在发送的电子邮件中包含适当数量的附件并且不会返回错误? Code examples would be helpful :)代码示例会有所帮助:)

And for clearer reference, here's the entire plugin file.为了更清晰的参考,这里是整个插件文件。 It's very light and uses no helper scripts.它非常轻巧,不使用任何帮助脚本。 Thank you all in advance!!谢谢大家!!

    <?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' );

?>

Just check if the extra attachment is set and skip the part if not:只需检查是否设置了额外的附件,如果没有,请跳过该部分:

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'];
}

to send attachements with wp_mail, try this用 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';
        }
    }
}

or another version with setting of the names of the attachements :或设置附件名称的其他版本:

        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';
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM