How to create a CSV on the fly and send as an attachment using wp_mail?

I’m trying to create a CSV file from a form submission and send that file automatically by email to a specific user. The email itself is sending fine, but I can’t get the attachment to go through. Is it possible to create an attachment without first saving the file to the server?

function create_csv() {
    $fd = fopen('php://temp/', 'w');
    if($fd === FALSE) {
        die('Failed to open temporary file');
    }

    $records = array( array('dummy', 'data', 'found', 'here') );

    fputcsv($fd, $headers);
    foreach($records as $record) {
        fputcsv($fd, $record);
    }

    rewind($fd);
    $csv = stream_get_contents($fd);
    fclose($fd);
    return $csv;
}

$to = $email;
$subject="Subject";
$message="Message";
$headers="From: " . $other_email;
$attachment = create_csv();

$sent = wp_mail($to, $subject, $message, $headers, $attachment);

1 Answer
1

That’s because wp_mail expects the attachment to be a filename (filepath) that it can attach and send. You are supplying a string containing the contents of the file:

function create_csv() {

    $filepath="/path/to/the/file.csv";

    $fd = fopen($filepath, 'w');
    if($fd === FALSE) {
        die('Failed to open temporary file');
    }

    $records = array( array('dummy', 'data', 'found', 'here') );

    fputcsv($fd, $headers);
    foreach($records as $record) {
        fputcsv($fd, $record);
    }

    rewind($fd);
    fclose($fd);
    return $filepath;
}

will solve your problem. See http://codex.wordpress.org/Function_Reference/wp_mail

Leave a Comment