Php mail attachment csv

A classic!

To send a CSV file as an attachment using PHP's mail() function, you can use the following code:

<?php

// Set the email headers
$headers = 'From: Your Name <[email protected]>'. "\r\n";
$headers.= 'Content-Type: text/csv; name="example.csv"'. "\r\n";
$headers.= 'Content-Disposition: attachment; filename="example.csv"'. "\r\n";

// Set the email body
$body = 'This is a test email with a CSV attachment.';

// Set the CSV file contents
$csv_data = array(
    array('Name', 'Email', 'Phone'),
    array('John Doe', '[email protected]', '123-456-7890'),
    array('Jane Doe', '[email protected]', '098-765-4321')
);
$csv_file = implode("\r\n", array_map(function($row) {
    return implode(',', $row);
}, $csv_data));

// Send the email
mail('[email protected]', 'Test Email', $body, $headers, $csv_file);

?>

In this example, we're setting the Content-Type header to text/csv and the Content-Disposition header to attachment to indicate that the file is an attachment. We're also setting the filename parameter to specify the name of the attachment.

The $csv_file variable contains the contents of the CSV file, which is created by iterating over the $csv_data array and using the implode() function to concatenate the rows and columns.

Finally, we're passing the $csv_file variable as the fifth argument to the mail() function, which will send the email with the CSV attachment.

Note that this code assumes that the CSV file is small enough to be sent as a single string. If your CSV file is large, you may need to use a different approach, such as sending the file as a binary attachment using the mime_content_type() function.