Send Email With Attachment is a frequent requirement in PHP application development, easily accomplished using PHP’s built-in mail() function. The mail() function enables developers to send emails with either text or HTML content and include one or more file attachments. The mail() requires three mandatory arguments: recipient information, message subject, and message body. Additionally, it supports two optional arguments: headers and parameters.
When the mail() function is called, PHP attempts to send the email immediately to the recipient. It returns true upon successful delivery and false if an error occurs during the process.
Send Email With Attachment
Syntex–
bool mail( $to, $subject, $message, $headers, $parameters );
Note – $headers, $parameters are optional arguments
Here’s a sample PHP code that demonstrates how to send an email with an attachment in PHP:
<?php
// recipient email address
$to = "recipient@example.com";
// subject of the email
$subject = "Email with Attachment";
// message body
$message = "This is a sample email with attachment.";
// from
$from = "sender@example.com";
// boundary
$boundary = uniqid();
// header information
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\".$boundary.\"\r\n";
// attachment
$attachment = chunk_split(base64_encode(file_get_contents('file.pdf')));
// message with attachment
$message = "--".$boundary."\r\n";
$message .= "Content-Type: text/plain; charset=UTF-8\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n\r\n";
$message .= chunk_split(base64_encode($message));
$message .= "--".$boundary."\r\n";
$message .= "Content-Type: application/octet-stream; name=\"file.pdf\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"file.pdf\"\r\n\r\n";
$message .= $attachment."\r\n";
$message .= "--".$boundary."--";
// send email
if (mail($to, $subject, $message, $headers)) {
echo "Email with attachment sent successfully.";
} else {
echo "Failed to send email with attachment.";
}
?>
In the code provided above, the recipient’s email address, subject, message body, and header information are specified. A boundary variable is used to separate the message from the attachment within the email structure.
The attachment is fetched from a file using file_get_contents() and encoded using base64_encode(). To facilitate transmission, the chunk_split() function divides the attachment into smaller segments.
Finally, the mail()
function sends the email with an attachment. If the email has been sent successfully, the function will return true
; Otherwise, it will return false
.
if above code will not work for any reason also try bellow code with form submit as attachment
if(isset($_POST['button']) && isset($_FILES['attachment']))
{
$from_email = 'sender@example.com'; //from mail, sender email address
$recipient_email = 'recipient@example.com'; //recipient email address
//Load POST data from HTML form
$sender_name = $_POST["sender_name"]; //sender name
$reply_to_email = $_POST["sender_email"]; //sender email, it will be used in "reply-to" header
$subject = $_POST["subject"]; //subject for the email
$message = $_POST["message"]; //body of the email
/*Always remember to validate the form fields like this
if(strlen($sender_name)<1)
{
die('Name is too short or empty!');
}
*/
//Get uploaded file data using $_FILES array
$tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server
$name = $_FILES['attachment']['name']; // get the name of the file
$size = $_FILES['attachment']['size']; // get size of the file for size validation
$type = $_FILES['attachment']['type']; // get type of the file
$error = $_FILES['attachment']['error']; // get the error (if any)
//validate form field for attaching the file
if($error > 0)
{
die('Upload error or No files uploaded');
}
//read from the uploaded file & base64_encode content
$handle = fopen($tmp_name, "r"); // set the file handle only for reading the file
$content = fread($handle, $size); // reading the file
fclose($handle); // close upon completion
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("random"); // define boundary with a md5 hashed value
//header
$headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version
$headers .= "From:".$from_email."\r\n"; // Sender Email
$headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back
$headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type
$headers .= "boundary = $boundary\r\n"; //Defining the Boundary
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $type; name=".$name."\r\n";
$body .="Content-Disposition: attachment; filename=".$name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";
$body .= $encoded_content; // Attaching the encoded file with email
$sentMailResult = mail($recipient_email, $subject, $body, $headers);
if($sentMailResult ){
echo "<h3>File Sent Successfully.<h3>";
// unlink($name); // delete the file after attachment sent.
}
else{
die("Sorry but the email could not be sent.
Please go back and try again!");
}
}
Thanks for reading