Use php to send emails with attachments

Source: Internet
Author: User

Refer to the online articles. As the saying goes, you will not copy a large copy of the article. The key is to use it for me. This is the most important thing. Let's go.
In fact, sending mail is very simple. php has ready-made functions. You can refer to the manual of php, especially the fourth example.
The key is how to combine uploaded attachments with email sending. For file upload, refer to the http://blog.csdn.net/slamdunk3/archive/2005/02/23/299025.aspx article.
Let's talk about the file upload Method and Its attributes:
Assume that the name of the file upload field is userfile, as shown in the preceding example. The name can be named at will.
The form can be written as follows:
<Input type = file name = userfile>
After submission, php uses the $ _ FILES array to automatically obtain relevant parameters:
$ _ FILES ['userfile'] ['name']
The original name of the client machine file.
$ _ FILES ['userfile'] ['type']
The MIME type of the file, which must be supported by the browser, for example, "image/gif ".
$ _ FILES ['userfile'] ['SIZE']
Size of the uploaded file, in bytes.
$ _ FILES ['userfile'] ['tmp _ name']
Temporary File Name stored on the server after the file is uploaded.
$ _ FILES ['userfile'] ['error']
The Error Code related to the file upload. ['Error'] is added in PHP 4.2.0.

Note: Before PHP 4.1.0, the array name is $ HTTP_POST_FILES, which is not an automatic global variable like $ _ FILES. PHP 3 does not support the $ HTTP_POST_FILES array.
When register_globals in php. ini is set to on, you can use more variables. For example, $ userfile_name is equivalent to $ _ FILES ['userfile'] ['name'], and $ userfile_type is equivalent to $ _ FILES ['userfile'] ['type. Remember that from PHP 4.2.0, the default value of register_globals is off. Therefore, we recommend that you do not rely on changing the settings to use the additional variables just mentioned.
After a file is uploaded, it is stored in the default temporary directory of the server by default, unless you set upload_tmp_dir in php. ini to another path. The default temporary directory of the server can be reset by changing the environmental variable TMPDIR of the PHP runtime environment. However, it does not work when you run the putenv () function in the PHP script. This environment variable can also be used to confirm that other operations are also performed on the uploaded file.
Now, let's look at the mail-related items. The following is an example of an email with an attachment (an HTML file.

Return-Path:
Date: Mon, 22 May 2000 19:17:29 + 0000
From: Someone
To: Person
Message-id: <83729KI93LI9214@example.com>
Content-type: multipart/mixed; boundary = "mongod983d6b89a"
Subject: Here's the subject
-- Mongod983d6b89a
Content-type: text/plain; charset = iso-8859-1
Content-transfer-encoding: 8bit

This is the body of the email.

-- Mongod983d6b89a
Content-type: text/html; name‑attachment.html
Content-disposition: inline; filename=attachment.html
Content-transfer-encoding: 8bit

 


This is the attached HTML file

 

-- Mongod983d6b89a --


The first seven lines are the mail headers. Note the Content-type header section. This header tells the email program that the email is composed of more than one part. Emails without attachments only have one part: the message itself. Electronics with attachments usually consist of at least two parts: messages and attachments. In this way, an email with two attachments is composed of three parts: the message, the first attachment, and the second attachment.

Different parts of emails with attachments are separated by a line. The demarcation line is defined in the Content -- type header. Each new part of the email starts with two hyphens (--) and a line.
There are two font numbers after the last line, indicating that there is no other part in the email.

There are some lines after each line to tell the mail program the content type.
For example, let's look at the two rows following the first demarcation line in the above example -- the rows starting with Content-type: text/plain. These lines describe part of the plain text of the ISO-8859-1 character set. The line following the second line tells the mail program that the current part is an HTML file named "attachment.html ".

Content-disposition indicates that the email program displays attachments in an embedded manner if possible. Now the new mail program will display HTML content after the message. If Content-disposition is set to attachment, the email program will not display the Content of the HTML file, but will display an icon (or something similar) connected to the file ). The recipient must click this icon to view the content of the attachment. In general, if the attachment contains some text (including HTML), Content-disposition will be set to inline, this is because most email programs can directly display attachments (text) without using other browsers. If the attachment is not a text (such as a part or other similar Content), Content-disposition is set to attachment.
We follow the example above and write a php program to process the recipient, sender, content, and attachment.
First, create a static page. The Code is as follows:
<Html>
<Body>
<Form method = post name = sndml action = sendmail. php ENCTYPE = "multipart/form-data">
<Table>
<Tr> <td> Sender: </td>
<Td> <input type = text name = from> </td>
</Tr>
<Tr> <td> receiver: </td>
<Td> <input type = text name = to> </td>
</Tr>
<Tr> <td> download prompt: </td>
<Td> <input type = text name = text> </td>
</Tr>
<Tr> <td> source data file: </td>
<Td> <input type = file name = upload_file size = 40> </td>
</Tr>
<Tr> <td> </td>
<Td> <input type = "submit" value = "OK">
</Td>
</Tr>
</Table>
</Form>
</Body>
</Html>
Note: ENCTYPE = "multipart/form-data" must be in the form.
Let's take a look at the php program that sent the mail:
<? Php
// Text content
$ Text = $ _ POST ['text'];
// Title
$ Subject = $ _ POST ['subobject'];
// Sender
$ From = $ _ POST ['from'];
// Recipient
$ To = $ _ POST ['to'];
// Attachment
$ File = $ _ FILES ['upload _ file'] ['tmp _ name'];
// Define the demarcation line
$ 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'];
Else
$ MimeType = "application/unknown ";
// File name
$ FileName = $ _ FILES ['upload _ file'] ['name'];

// Open the file
$ Fp = fopen ($ file, "r ");
// Read the entire file into a variable
$ Read = fread ($ fp, filesize ($ file ));
// We use base64 to encode it.
$ Read = base64_encode ($ read );
// Cut the long string into small pieces consisting of 76 characters in each line
$ Read = chunk_split ($ read );
// Now we can create the subject of the email
$ Body = "-- $ boundary
Content-type: text/plain; charset = iso-8859-1
Content-transfer-encoding: 8bit
$ Text
-- $ Boundary
Content-type: $ mimeType; name = $ fileName
Content-disposition: attachment; filename = $ fileName
Content-transfer-encoding: base64
$ Read
-- $ Boundary --";
// Send an email
If (mail ($ to, $ subject, $ body, $ headers ))
Print "OK! The mail $ from --- $ to has been send <br> ";
Else
Print "fail to send mail <br> ";
?>
It doesn't matter if you don't understand it. Let me explain:
1. mail header construction: generally includes
Content-type is used to send attachments. Setting it to multipart/mixed indicates multiple parts (the email itself + the attachment ).
Boundary is the demarcation line mentioned above. His value is obtained using the uniqid (); function provided by php.
Receiver, Cc, etc., followed by From: Cc :. Use \ r \ n to separate the Content-type boundary.
2 email body
For plain text emails, the format is as follows:
Content-type: text/plain; charset = iso-8859-1
Content-transfer-encoding: 8bit
Followed by the text of the email.
If the attachment is:
Content-type: $ mimeType; name = $ fileName
Content-disposition: attachment; filename = $ fileName
Content-transfer-encoding: base64
Then add the attachment content.
$ MimeType is the MIME type of the attachment. You can use $ _ FILES ['upload _ file'] ['type'] to obtain the file.
$ FileName is the attachment name.
The mail text and attachments are separated by boundary.
Someone may ask, what is the content of the attachment? The attachment content is read by using the read function, and then it is base64-encoded and then chunk_split to unload N parts. Each part is 76 characters by default.
Okay. Now let's look at that program. Should it be okay? Put the corresponding variables into the mail function.
The above program passed the test in PHP Version 4.3.8 freeBSD.
Reference: php emails with attachments: 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: info-contact@alibabacloud.com 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.