Everybody probably knows how to send an email using PHP, but do you know how to send an email with an attachment?
This is actually not very difficult and you can find examples all over the web. However, it seems that all the examples I found didn’t work! 🙁
But after some debugging and testing, I finally got a working solution. 😀
Please see below the code with comments:
// Define some variables $to = 'test@logikdev.com' $subject = 'Test email'; // Create a boundary string. It must be unique so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); // Define the headers $headers = "From: noreply@logikdev.com\r\n"; // Add boundary string and mime type specification $headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; // Read the attachment file contents into a string, encode it with MIME base64, and split it into smaller chunks $attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); // Define the body of the message $message = " --PHP-mixed-$random_hash Content-Type: text/plain; charset='iso-8859-1' This is a test email message sent with PHP. --PHP-mixed-$random_hash Content-Type: application/zip; name=attachment.zip Content-Transfer-Encoding: base64 Content-Disposition: attachment $attachment --PHP-mixed-$random_hash--"; // Send the email if (@mail($to, $subject, $message, $headers)) { echo "The mail has been sent."; } else { echo "The mail has NOT been sent!"; }
#1 by malli on 23 May 2012 - 11:34
Thnks full to you
#2 by Arjun Dhiman on 20 Mar 2013 - 06:20
Thanks buddy, After a lot of problem, I have send mail content with attachment by your help. again thanks
#3 by Beuqui on 01 Nov 2013 - 16:56
Thanks Thanks Thanks!!!!! You save my life!!!!