Send an email with an attachment in PHP

Source: Internet
Author: User
Tags base64 character set contains header mail mixed

I often hear such a question: "I have a contract from the website." How do I add an attachment to an e-mail message sent through a form? "
The first thing I want to say is that there is no easy way to do this. You have to be very good at understanding PHP or
Other server-side scripting languages. And, of course, you need an account for a website that really supports PHP. If this is the case, you can use PHP to send an email with an attachment after you have finished reading this chapter.

1. How the annexes work

If you've ever searched the "attachment" function in a PHP manual, the result may be nothing (at least not for the time that I write this article). Later on you will spend a lot of time to understand this knowledge.

You might think that when you send an e-mail to someone with an attachment, attachments are placed with the mail in the recipient's mailbox (for example, if you send him/her a PNG image file, his/her mailbox will contain a TXT file (email) and a. png file (attachment)). But that's not how it works. When you add an attachment, your mail program converts the attachment to a plain text file and inserts the text block after the content you write (the actual email). This, when you send out everything, the recipient's mailbox has only a plain text file--a file that contains both the attachment and the actual e-mail content.

The following is an example of an e-mail message with an attachment (an HTML file). I've labeled a few of these important lines:

Return-path: <someone@example.com>
Date:mon 2000 19:17:29 +0000
From:someone <someone@example.com>
To:person <person@eksempel.dk>
Message-id: <83729ki93li9214@example.com>
content-type:multipart/mixed; boundary= "396d983d6b89a"
Subject:here ' s the subject

--396d983d6b89a
Content-type:text/plain; Charset=iso-8859-1
Content-transfer-encoding:8bit

This is the body of the email.

--396d983d6b89a
content-type:text/html; Name=attachment.html
Content-disposition:inline; Filename=attachment.html
Content-transfer-encoding:8bit

<title>the attachment</title>
<body>
</body>

--396d983d6b89a--

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.

2. Use PHP to generate email with attachments

Here's an example that tells you if you add a defined HTML file as an attachment to a message:

<?php
# We first write the actual message content
$emailbody = ' This is text ' goes into the ' body of the ' email.

# and then we're going to be an attachment to the HTML file
$attachment = "<title>the attached file</title>
<body>
</body>

# Establish a dividing line separating different parts of the message.
# Basically, the dividing line can be any string.
# But the important thing is to identify a person who writes emails
# This will be a random string to write, so we use
# uniqid function to produce a random string.
$boundary = Uniqid ("");

# Now we're going to build headers. Don't forget to insert the
# Content-type header to indicate that this message contains one or more attachments.
$headers = "from:someone@example.com
content-type:multipart/mixed; Boundary=\ "$boundary" ";

# Well, now we've got all the content of the mail.
# The next thing is to change the body of the message.
$emailbody = "--$boundary
Content-type:text/plain; Charset=iso-8859-1
Content-transfer-encoding:8bit

$emailbody

--$boundary
content-type:text/html; Name=attachment.html
Content-disposition:inline; Filename=attachment.html
Content-transfer-encoding:8bit

$attachment

--$boundary--";

# Now you can send out the mail
Mail ("person@eksempel.dk", "the subject", $emailbody, $headers);
?>

3. The file uploaded by the user as an attachment

You may find the above example difficult to understand, but below .... In the example below, it's more difficult because we're going to use a form to let users upload their files and make this file an attachment to the email we're sending. The trouble is that we can't know the MIME type of the file in advance. In the previous example, we already know that it is an HTML file, so it is easy to set the Content-type header for this attachment. In the following example, the MIME type may be arbitrary, because the user may upload an HTML file, a PNG file, a vcard file, or something else. Let's take a look at the example:

<?php
# Now we'll build the form. When you generate a form that can upload files,
# Don't forget to set the "Enctype" property of the <form> label to "Multipart/form-data".
echo "<form action= ' $php _self ' enctype= ' multipart/form-data ' method= ' post ' >\n ';
echo "<input type= ' text ' name= ' from ' ><br>\n";
echo "<input type= ' text ' name= ' to ' ><br>\n";
echo "<input type= ' text ' name= ' subject ' ><br>\n";
echo "<input type= ' file ' name= ' attachment ' ><br>\n";
echo "<textarea name= ' body ' ></textarea><br>\n";
echo "<input type= ' submit ' name= ' send ' value= ' send ' >\n";
echo "</form>\n";

# If the user has pressed the ' Send ' button '
if ($send) {
# define dividing line
$boundary = Uniqid ("");

# Generate Message Headers
$headers = "From: $from
content-type:multipart/mixed; Boundary=\ "$boundary" ";

# Determine the MIME type of the uploaded file
if ($attachment _type) $mimetype = $attachment _type;
# If the browser does not specify a MIME type for the file,
# we can set it to ' Application/unknown '.
else $mimetype = "Application/unknown";

# Determine the name of the file
$filename = $attachment _name;

# Open File
$fp = fopen ($attachment, "R");
# Read the whole file into a variable
$read = Fread ($fp, FileSize ($attachment));

# Well, now the variable $read is a block of text that contains the entire contents of the file.
# Now we're going to convert this text block into a format that the mail program can read.
# We use the Base64 method to encode it
$read = Base64_encode ($read);

# Now we have a long string encoded with the Base64 method.
# The next thing is to cut this long string into small chunks of 76 characters per line.
$read = Chunk_split ($read);

# Now we can build the body of the message
$body = "--$boundary
Content-type:text/plain; Charset=iso-8859-1
Content-transfer-encoding:8bit

$body

--$boundary
Content-type: $mimetype; Name= $filename
Content-disposition:attachment; Filename= $filename
Content-transfer-encoding:base64

$read

--$boundary--";

# Send mail
Mail ($to, $subject, $body, $headers);
}
?>


That's the whole story. If you don't understand the above example, my advice is to send you a few emails with attachments, and then carefully study the source code of the message.



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.