Send an email with an attachment in PHP

Source: Internet
Author: User
Tags array base64 character set error code file upload header variables variable


actually mail is very simple, PHP has ready-made functions, you can refer to PHP manual, especially the fourth example, said very detailed. The key to
is how to combine upload attachments with mail delivery. About the file upload, you can refer to this article.
Talk about file upload methods and their properties:
Let's assume the name of the file upload field, as shown in the previous example, is UserFile. Names can be named arbitrarily.
forms can be written in this way:
<input type=file name=userfile>
Submit, PHP uses $_files array to automatically obtain relevant parameters:
$_files[' userfile ' [' Name ']
The origin of the client machine file. The MIME type of the
$_files[' userfile ' [' type ']
file requires the browser to provide support for that information, such as "Image/gif". The size, in bytes, of the uploaded file of
$_files[' userfile ' [' Size ']
. The temporary file name that is stored on the server after the
$_files[' userfile ' [' tmp_name ']
file is uploaded.
$_files[' userfile ' [' Error ']
and the file upload associated error code. [' ERROR '] is added in PHP version 4.2.0.

Note: Before PHP version 4.1.0, the name of the array is $HTTP _post_files, and it is not an automatic global variable like $_files. $HTTP _post_files Array is not supported in PHP 3.
When the register_globals in PHP.ini is set to ON, you can use more variables. For example, $userfile _name is equivalent to $_files[' userfile ' [' name '], $userfile _type equivalent to $_files[' userfile '] [' type '], and so on. Keep in mind that starting with PHP 4.2.0, the default value of Register_globals is off, so we recommend that you do not rely on the modifier to use the additional variables just mentioned.
When a file is uploaded, it is stored by default in the default temp directory on the server, unless you set the Upload_tmp_dir in php.ini to a different path. The default temp directory for the server can be reset by changing the environment variable tmpdir of the PHP run environment, but setting by running the putenv () function inside the PHP script does not work. The environment variable can also be used to confirm that other operations are also performed on uploaded files.
With these, we look at the mail-related things. The following is an example of an e-mail message with an attachment (an HTML file).

Date:mon 2000 19:17:29 +0000
Message-id: <>
content-type:multipart/mixed; boundary= "396d983d6b89a"
Subject:here ' s The Subject
Content-type:text/plain; Charset=iso-8859-1

This is the body of the email.

content-type:text/html; Name=attachment.html
Content-disposition:inline; Filename=attachment.html

This is the attached HTML file


The first 7 lines are the headers of the message, which is notable for the Content-type header. This header tells the Mail program that the email is made up of more than one part. There is only one part of a message that does not contain attachments: the message itself. Electrons with attachments usually consist of at least two parts: messages and attachments. In this way, a message with two attachments consists of three parts: message, first attachment and second attachment.

Separate parts of an e-mail message with attachments are separated by a dividing line. The dividing line is defined in the Content--type header. Each new part of the message starts with a two hyphen (-) and a dividing line.
There are also two hyphens after the last line, which means there is no other part of the message.

After each line there are rows that tell the mail program the type of content in this section.
For example, look at the two lines following the first line in the example above-the line that begins with Content-type:text/plain. These lines describe the following sections as plain text for the iso-8859-1 character set. The line following the second line tells the Mail program that the current part is an HTML file whose name is "attachment.html".

Content-disposition this tells the mail program to display attachments in an inline manner if possible. The new mail program now displays HTML content after the message. If the content-disposition is set to attachment, then the mail program will not display the contents of the HTML file, but instead display an icon (or something else) connected to the file. The recipient must click on this icon to see the contents of the attachment. In general, if the attachment is some text (including HTML), the content-disposition is set to inline, because most mail programs now have the ability to display the contents of the attachment (text) directly without resorting to other browsers. If the attachment is not text (such as a picture or other similar content), Content-disposition is set to attachment.
We modeled the above example, we write a PHP program, you can submit to the recipient, sender, letter content, accessories to deal with.
First, create a static page with the following code:
<form method=post name=sndml action=sendmail.php enctype= "Multipart/form-data" >
<tr ><td> Sender:</td>
<td><input Type=text Name=from ></td>
&LT;TR ><td> Recipient:</td>
<td><input Type=text name=to ></td>
<tr ><td> Download Tips:</td>
<td><input Type=text Name=text ></td>
&LT;TR ><td> source data file:</td>
<td><input type=file Name=upload_file size=40></td>
<tr><td> </td>
<td><input type= "Submit" value= "OK" >
To be aware of: the form of enctype= "Multipart/form-data" must have.
Let's take a look at the PHP program that sends the mail:
Text content
$text = $_post[' text '];
$subject = $_post[' subject '];
Sent by
$from = $_post[' from '];
Accepted by
$to = $_post[' to '];
$file = $_files[' upload_file '] [' tmp_name '];
Defining boundaries
$boundary = Uniqid ("");
$headers = "content-type:multipart/mixed; boundary= $boundary \ r \ n ";
$headers. = "From: $from \ r \ n";
Determine the MIME type of the uploaded file
if ($_files[' upload_file '] [' type '])
$mimeType = $_files[' upload_file '] [' type '];
$mimeType = "Application/unknown";
$fileName = $_files[' upload_file ' [' name '];

Open File
$fp = fopen ($file, "R");
Read the entire file into a variable
$read = Fread ($fp, FileSize ($file));
We use the Base64 method to encode it.
$read = Base64_encode ($read);
Cut this long string into small chunks of 76 characters per line
$read = Chunk_split ($read);
Now we can create the body of the message
$body = "--$boundary
Content-type:text/plain; Charset=iso-8859-1
Content-type: $mimeType; Name= $fileName
Content-disposition:attachment; Filename= $fileName
Send mail
if (Mail ($to, $subject, $body, $headers))
Print "ok! The Mail $from---$to has been send<br> ";
Print "fail to send mail <br>";
Do not understand that it does not matter, let me explain:
1, the structure of the message header: generally include
Content Type (Content-type) to send an attachment, set to multipart/mixed meaning is more than one part (the message itself + attachment).
Boundary, is the line mentioned above, his value with PHP uniqid ();
Recipient, CC, etc., followed by FROM:CC:. Split with \ r \ n with the content-type boundary above.
2 Mail Body
If the message content is plain text it has the following format:
Content-type:text/plain; Charset=iso-8859-1
Then followed by the text content of the message.
If it is an attachment:
Content-type: $mimeType; Name= $fileName
Content-disposition:attachment; Filename= $fileName
followed by the addition of attachment content.
$mimeType is the MIME type of the attachment. can be obtained by $_files[' upload_file ' [' type '].
$fileName's the name of the accessory.
The message text content and attachment are separated by boundary.
Some people will ask, what is the attachment content? The attachment content is to read the uploaded attachment with the Read function, and then pass it through the base64 encoding and then use Chunk_split to unload the n block, each block size is the default 76 characters.
OK, now go to see the procedure, should be no problem? It's OK to bring the corresponding variable into the mail function.
The above program is tested through PHP Version 4.3.8 FreeBSD.
Reference article: "PHP send the mail with the attachment author: cn-linux"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.