Generate CSV and directly send to Mail WordPress

In this blog, you’ll learn how to generate CSV with database of WordPress and csv file directly send to mail as attachment.

This blog divide in two part 1st is Generate CSV and 2nd is attach to mail for send to user with the help of WordPress of PHP functions.

Generate CSV or URL

Copy the code from below and paste in your functions.php or file. For the path of updated CSV file use <?php echo create_csv(); ?>. This function update your dynamic data (values form databse) to CSV file.

function create_csv() {
    global $wpdb;  
    $filepath = '/path/report.csv';
    $fd = fopen($filepath, 'w');
    if($fd === FALSE) {
        die('Failed to open temporary file');
    $records = $wpdb->get_results("SELECT * FROM `table_name`", ARRAY_A);
    fputcsv($fd, array('Field A', 'Field B', 'Field C'));
    foreach($records as $key => $value) {
        $modified_values = array(
        fputcsv($fd, $modified_values);
    return $filepath;

$wpdb (WordPress database access abstraction class)

$filepath = ‘/path/report.csv’; First you have to create black CSV file or download blank CSV file from here or upload in any folder in your server.

/path/: For path you can use $_SERVER[‘DOCUMENT_ROOT’] or copy “/nas/wp/www/sites/Your Theme Folder Name“.

Attach to mail

For send a mail in WordPress see :

$to = '';
$subject = 'Generate report';
$headers = "From: Shivam Khare <>\r\n";
$headers .= "Reply-To:\r\n";
$headers .= "CC:\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html>
  <title>List of New Price Changes</title>
$attachment = create_csv();
$sent = wp_mail($to, $subject, $body, $headers,$attachment);
if($sent) {
   echo 'message sent!';
   echo 'message not sent!';

$attachment = create_csv(); This is the code for assign path of updated CSV file to attachment variable of WordPress.