If you have made it this far, you will be pleased to know that you are just inches away from adding proper attachments to your email. In fact, rather than add explanation and keep you waiting, I am going to jump right in. Add this line after the call to setHTMLBody() :
$message->addAttachment("<some pic>");
You will of course need to change <some pic> to the name of a picture file in the same directory as the script. And... you are done! That is all it takes to add an attachment once you are using PEAR::Mail and PEAR::Mail_Mime, so I hope you will agree it was worth the effort to get this far.
If you run the script again, you should see the attachment has come through properly. However, there is one more thing you can do with PEAR::Mail_Mime and attachments, and that is to attach HTML images. These are essentially the same thing as attachments, except they are not shown as an attachment most HTML-compliant mail readers - they are shown only in the message body. This makes better sense for HTML pictures, because it would likely confuse people to see a dozen pictures attached to the mail that aren't of importance.
To add a HTML picture, use the addHTMLImage() function. As with addAttachment(), this takes the filename to attach as its only parameter. In order to use this picture, you need to edit the HTML file you are attaching and add the appropriate line, e.g.:
// in the PHP file: $message->addHTMLImage("button.png"); // and in the HTML file: <IMG SRC="button.png" />
Now when you send the mail, button.png should be sent along too and displayed inside the message. In Outlook, this results in the first picture file being attached, and the second file being attached (but not listed as an attachment) and shown inside the message - perfect!
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Reading mail >>
Previous chapter: Sending mixed-type messages with PEAR::Mail_Mime
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.