Attach excel sheet with php mail

To attach an Excel sheet to a PHP mail, you'll need to use the mime_content_type and base64_encode functions to encode the file, and then use the Content-Type and Content-Disposition headers to specify the attachment.

Here's an example code snippet that demonstrates how to do this:

<?php

// Set the email headers
$headers = array(
    'From' => '[email protected]',
    'To' => '[email protected]',
    'Subject' => 'Example Email with Excel Attachment',
    'Content-Type' => 'text/plain; charset=UTF-8',
    'Content-Disposition' => 'attachment; filename="example.xlsx"'
);

// Set the email body
$body = 'This is an example email with an Excel attachment.';

// Read the Excel file
$file = 'example.xlsx';
$fp = fopen($file, 'rb');
$file_contents = fread($fp, filesize($file));
fclose($fp);

// Encode the file using base64
$file_encoded = base64_encode($file_contents);

// Set the attachment headers
$headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$headers['Content-Disposition'] = 'attachment; filename="'. $file. '"';

// Send the email
mail('[email protected]', 'Example Email with Excel Attachment', $body, implode("\r\n", $headers));

?>

In this example, we're using the fopen and fread functions to read the Excel file, and then encoding it using base64_encode. We're then setting the Content-Type and Content-Disposition headers to specify the attachment.

Note that you'll need to replace example.xlsx with the actual path to your Excel file, and [email protected] with the actual email address of the recipient.

Also, make sure to check the email client's settings to ensure that it can handle attachments with the .xlsx extension.

Alternatively, you can use a library like PHPMailer to send the email with the attachment. Here's an example:

<?php

require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';

$mail->setFrom('[email protected]');
$mail->addAddress('[email protected]');

$mail->Subject = 'Example Email with Excel Attachment';
$mail->Body = 'This is an example email with an Excel attachment.';

$mail->addAttachment('example.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'attachment', 'example.xlsx');

$mail->send();

?>

In this example, we're using the PHPMailer library to send the email with the attachment. We're setting the addAttachment method to specify the attachment file, and the Content-Type and Content-Disposition headers are automatically set by the library.