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 first order of business is to initialize some variables and provide a constructor for the class.
<?php class mime_mailer { var $from; var $to; var $subject; var $body = ""; var $headers; var $files = array(); var $header_set = false; var $body_set = false;
Some of these are pretty self explanatory. It's easy to see who the email is from, who it goes to, the subject and the body of the message. Other variables are provided for headers, an array is for file contents and two boolean values are intended as checks to determine that we have everything before sending the mail. It might be useful in some situations to employ email address validation before sending to help ensure that nothing goes wrong. Next is the constructor method.
As long as all the necessary values are valid, several variables are set with the constructor. In addition the "set_body()" method is called in order to place the body of the message inside the proper mime content. The "MIME_BOUNDRY" marks individual sections of the mail. Use two line returns before and after each content block (this goes for the attachment content as well).
The "set_headers()" method is also called to set some necessary mail headers. Values for email "from", "Reply-To" "X-Sender" and "Return-Path" are set from the "from" variable we set earlier.