HomePHP Page 2 - Sending Email with PHP Networking
Sending mail with PHP - PHP
In this article we will look at the protocol that is involved in sending email messages. We will also examine the thorny issue of how to send an attachment with an email message. This article is the second of two parts.
Now that we know what tools PHP provides, let's write a quick application that will help us send messages with attachments. In order to send a message with an attachment, you need to send a mail header instructing that the email be sent as an attachment. A header might look like this:
The header instructs the email to send the message as an attachment with a file called myfile.doc. So if you want to send a short message with an attachment, this is how it could look:
$message = "This is my first test of the mail() function.";
$headers ="Content-disposition: attachment;
filename=myfile.docn";
$headers .= "cc:salles@mycompany.comn";
$result=mail($to, $subject, $message, $headers);
?>
Another very important step that you need to take when sending attachments is to set the content type for the file. The following are the available content types:
image/gif
image/jpeg
audio/x-wav
audio/vnd.rn-realaudio
video/mpeg
video/avi
You also may want to send application files. Some are text files, and some are binary files. For example, an RTF file is a text file, whereas a Word document is a binary file. Generally binary files are of type applica/octed stream. Binary files require encoding when they are sent through an email. PHP provides us with a function called chunk_split(), that does just that:
$encode = chunk_split(base64_encode($string));
In addition, when sending an encoded file, you need to inform the mail software that you intend to sent a encoded file. This is done in the headers section of the mail function: