To send an email with an attachment in PHP, you can use the mail() function in combination with the multipart/mixed MIME type for the email. Here’s an example of how to send an email with an attachment:

<?php
// Recipient email address
$to = "recipient@example.com";

// Subject of the email
$subject = "Sending an email with attachment";

// Message body
$message = "Please find the attached file.";

// Additional headers
$headers = "From: your_email@example.com\r\n";
$headers .= "Reply-To: your_email@example.com\r\n";

// Boundary for separating different parts of the email
$boundary = md5(time());

// Content-Type headers for email
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

// Message content
$email_body = "--$boundary\r\n";
$email_body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$email_body .= $message . "\r\n";

// Path to the file you want to attach
$attachment_path = "/path/to/your/file.pdf";

// Read the file content
$file_content = file_get_contents($attachment_path);

// Encode the file content for email
$encoded_file = chunk_split(base64_encode($file_content));

// Attach the file
$email_body .= "--$boundary\r\n";
$email_body .= "Content-Type: application/pdf; name=\"" . basename($attachment_path) . "\"\r\n";
$email_body .= "Content-Disposition: attachment; filename=\"" . basename($attachment_path) . "\"\r\n";
$email_body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$email_body .= $encoded_file . "\r\n";
$email_body .= "--$boundary--";

// Send the email
if (mail($to, $subject, $email_body, $headers)) {
    echo "Email with attachment sent successfully.";
} else {
    echo "Email with attachment could not be sent.";
}
?>

Make sure to replace "recipient@example.com", "your_email@example.com", and "/path/to/your/file.pdf" with the recipient’s email address, your own email address, and the path to the file you want to attach.

This code creates a multipart email with a plain text message and an attached file. The file is encoded in base64 and included as an attachment in the email.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *