Search code examples
phpxmlwordpresscontact-form-7

Wordpress send XML file to email


I'm trying to achieve this result: I'm using contact form 7 and I want that when you click on "Submit", you don't receive the email in plaintext, but an .xml file containing all the information. As a workaround for the xml file I'm using that function:

add_action( 'wpcf7_before_send_mail', 'CF7_pre_send' );

function CF7_pre_send($cf7) {
   $output = "";
   $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>Name: " . $_POST['your-name'];
   $output .= "Email: " . $_POST['your-email'];
 $output .= "Message: " . $_POST['your-message'];

 file_put_contents("cf7outputtest.xml", $output);
}

So that's generates the xml file but I'm able to save it only in the wordpress directory, or in a specific path. Is there a way or a workaround to send this xml directly to an email address?

Thanks in advance,

Luca


Solution

  • After it has generated the file, the function can send it using the wp_mail function.

    add_action( 'wpcf7_before_send_mail', 'CF7_pre_send' );
    
    function CF7_pre_send($cf7) {
       $output = "";
       $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>Name: " . $_POST['your-name'];
       $output .= "Email: " . $_POST['your-email'];
     $output .= "Message: " . $_POST['your-message'];
    
     file_put_contents( "cf7outputtest.xml", $output);
    
       // then send email
       $to = "[email protected]";
       $subject = "The subject";
       $body = "The email body content";
       $headers = "From: My Name <[email protected]>" . "\r\n";
    
       $attachments = array( "cf7outputtest.xml" );
    
       wp_mail( $to, $subject, $body, $headers, $attachments );
    }