How to send message with attachment
A lot of developers faced with such a problem, that’s why there are a lot of solutions. A lot of them have different mistakes and some of them are very complicated. But the most important minus is that many developers having written class that satisfies their requirements never try to support or revision of the initial codes.
That’s why further examples will base on solution taken from PEAR. Here is an example:
<?php
include("Mail.php");
include("Mail/mime.php");
$text = "Text version of email";
$html = "<html><body>HTML version of email</body></html>";
$file = "/home/richard/example.php";
$crlf = "\r\n";
$hdrs = array(
"From" => "you@yourdomain.com",
"Subject" => "Test mime message"
);
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, "text/plain");
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$mail =& Mail::factory("mail");
$mail->send("postmaster@localhost", $hdrs, $body);
?>
Let’s view addAttachment method more in detail. Accepted parameters:
- string $data
- string $c_type
- boolean $isfile
- string $encoding
Full way to the attached file on the server. Obligatory parameter.
Content-type header value that will be sent. It is non-obligatory parameter. Its default value is application/octet-stream.
Defines whether first parameter is the way to the file. It is non-obligatory parameter. Its default value is true
Content-Transfer-Encoding header value that defines the format of the application sending. It is non-obligatory parameter. Permissible values are base64, quoted-printable. Its default value is base64.
Thus there are two ways of utilization of that method.
- defining the way to the file on the server
$mime->addAttachment("/home/user/report.txt", "text/plain"); - defining file content
$mime->addAttachment($contentFile, "text/plain", "report.txt", false);
Now we turn to header and body forming. It is still charge of Mail_mime class copy. If you want to form the body of the message you have to use get method. Keys can be as follows: text_encoding, html_encoding, 7bit_wrap, text_charset, html_charset. If you want to form the header of the message you have to use headers method.
get() method should be called earlier then headers() method. Make sure that it is kept in your code.
The process of message sending is trusted on Mail class. At first with the help of static calling of factory method you have to create a copy of given class. In our example it has only one parameter - line ‘mail’.
Message sending process finishes with the calling of send method.
If you want to check errors during mail sending you can use following code:
<?php
$status =$mailer->send("user@your.domain.com", $headers, "your message");
if (PEAR::isError($status)) {
print("***ERROR");
}
?>



