How to send attachment in mail using php from localhost

To send an email with an attachment using PHP from your localhost, you'll need to follow these steps:

Step 1: Set up your PHP mail configuration

In your php.ini file, make sure the following settings are enabled:

Step 2: Create a PHP script to send the email

Create a new PHP file (e.g., send_email.php) with the following code:

<?php
// Define the email settings
$to = '[email protected]';
$subject = 'Test Email with Attachment';
$message = 'This is a test email with an attachment.';

// Define the attachment file
$attachment = 'path/to/attachment/file.pdf';

// Set the email headers
$headers = array(
    'From' => '[email protected]',
    'Reply-To' => '[email protected]',
    'Subject' => $subject,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8'
);

// Set the email body
$body = $message;

// Read the attachment file
$fp = fopen($attachment, 'rb');
$attachment_data = fread($fp, filesize($attachment));
fclose($fp);

// Set the attachment headers
$headers['Content-Disposition'] = 'attachment; filename="'. basename($attachment). '"';
$headers['Content-Type'] = 'application/octet-stream';
$headers['Content-Length'] = filesize($attachment);

// Send the email
mail($to, $subject, $body, implode("\r\n", $headers), $attachment_data);

echo 'Email sent successfully!';
?>

Step 3: Run the PHP script

Open a terminal or command prompt and navigate to the directory where you saved the send_email.php file. Run the script using the following command:

php send_email.php

This will send the email with the attachment to the specified recipient.

Tips and Variations