2

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);
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.