"The person who took the initiative and found solutions has been promoted several times." Catherine Pulsifer
LogikDevelopment
Posts Tagged boundary
Send email attachment with PHP
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!"; }
Share this
Archives
- March 2014 (2)
- September 2013 (1)
- August 2013 (1)
- July 2013 (1)
- June 2013 (1)
- February 2013 (1)
- January 2013 (1)
- December 2012 (1)
- September 2012 (1)
- August 2012 (1)
- June 2012 (1)
- May 2012 (1)
- April 2012 (3)
- February 2012 (1)
- December 2011 (3)
- November 2011 (2)
- October 2011 (2)
- September 2011 (2)
- July 2011 (1)
- June 2011 (2)
- May 2011 (2)
- April 2011 (2)
- March 2011 (2)
- February 2011 (2)
- January 2011 (2)
- December 2010 (1)
- November 2010 (2)
- October 2010 (3)
- September 2010 (1)
- August 2010 (2)
- July 2010 (1)
- June 2010 (2)
- May 2010 (3)
- March 2010 (2)
- February 2010 (3)
- January 2010 (2)
- December 2009 (3)
- November 2009 (3)
Tags
Ajax Amazon S3 Arch Linux backup bash benchmarking Bug cron D-Link decryption DNS-313 DNS-323 encryption Html Internet Explorer IOzone Java JavaScript javax.crypto JSF Linux locale Mac OS X Monitoring MyFaces MySQL OAuth onclick OpenSolaris PHP Raspberry Pi RichFaces s3sync Samba shell SQL Server Tomcat Twitter Twitter4J UTF-8 VBScript virtual storage pool Windows Zabbix zpool