Setting up a web application to send plain text email is easy. What if you need the email to handle other content, such as images or special document formats? This article explains how to design a PHP class for sending email with attachments.
The final two methods send the mail. If the proper headers and body information is set, the mail message is assembled from all the information previously gathered. The "assemble()" method is called to assemble the attachment data and put it together with the body of the message.
Formatting can be important to the success of the mailing. Attachments can fail to appear or be corrupted if the output is not correct. If you have any trouble while modifying or adding to this class, consult documentation about mime formatting to determine what might have gone wrong.
The Code in Use
Using the mime_mailer class is a simple matter. The first line you will need is to include the file in your application. You then initialize an instance of the class, add your attachments and send the mail. Use as many instances as you need. The to, from, subject and body information can come from any source in your application you need it to.
include("class/mime_mailer.php"); $to = "firstname.lastname@example.org"; $from = "email@example.com"; $subject = "Season's Greetings"; $body = "Here's some xmas cards just for you!"; $mailer = new mime_mailer($to,$from,$subject,$body); $mailer->add_attachment("cards/xmascard.pdf"); $mailer->add_attachment("cards/xmascard2.gif"); $mailer->send();
No Stamps to Lick
There are quite a few applications where this basic functionality would be indispensable. Wrapping it all up into just a few lines can save a lot of time and effort. Experiment with the code, use it in your applications, and if you have any modifications that you think will be useful to others, please share them, and please email responsibly.