PHP

How to Send Email With Attachment in PHP


In this article, you will learn how to send email with attachment in PHP. You need to ensure that you have configured your local installation for sending and receiving emails.

Send Email With Attachment

In order to send email with attachment, you can use the mail() method.

// Name of file attachment
$filename = "test.txt";

// Local path to file attachment
$path = "C:\Users\Codesource\Desktop";

// Full local path to file attachment
$file = $path.$filename;

// File contents
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// Sender's name
$from_name = "Codesource";

// Sender's email
$from_mail = "codesource@example.com";

// Recipient's email
$reply_to = "recipient@example.com";

// Recipient's email
$mail_to = "recipient@example.com";

// Email Subject
$subject ="Email with Attachment";

// Headers for email
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// Messages and attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

// If email with attachment has been sent
if (mail($mail_to, $subject, $nmessage, $header)) {

	// Display sent message
    echo "The email with attachment has been sent.";
    
// Else if email with attachment cannot be sent
} else {

	// Display failed to be sent message
    echo "The email with attachment failed to be sent";
}

Note: The mail() method functions by sending an email directly from a script.


Share on social media

//