如何使用wp_mail动态创建CSV并将其作为附件发送?

时间:2015-03-01 作者:harvestthemoon

我正在尝试从表单提交创建CSV文件,并通过电子邮件自动将该文件发送给特定用户。电子邮件本身发送得很好,但我无法通过附件。是否可以在不首先将文件保存到服务器的情况下创建附件?

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 个回复
SO网友:Saurabh Shukla

这是因为wp\\U mail希望附件是一个文件名(filepath),它可以附加并发送。您正在提供一个包含文件内容的字符串:

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;
}
会解决你的问题。看见http://codex.wordpress.org/Function_Reference/wp_mail

结束

相关推荐

Email notification

我正在尝试用主题(帖子标题)和内容来丰富此通知,而不是它的当前视图和编辑链接,有人能帮忙吗?<?php function __notify_admin_on_publish( $new_status, $old_status, $ticket ) { if ( $new_status != \'publish\' || $old_status == \'publish\' ) return; $message = \'View it