Home > Article > Backend Development > Pear Mail Send email with attachments_PHP tutorial
Add attachment
Add an attachment
Add one or Multiple attachments are very simple. To add attachments, you call the addAttachment method. This method can be called multiple times to add multiple attachments.
boolean addAttachment($file string, string[$c_type='application/octetstream'], string[$name= ], boolean [$isfile = true], string [$encoding = 'a base64'])
Variables:
$file: Either the variable contains the contents of a file, or the path to the file itself
$ c_type: Content type, which means, for example, the MIME type of the file. text/plain, text/csv, app/pdf
$name: the name of the file you Want it to appear in the email, this should be unique
$ isFile: Whether the variable $file is the path to the file or the contents of the file
$encoding: This should usually be left as the default unless you know what you are doing
Attachments can be stored in a variable, or in a file on the server File system. In this first example, I will create a small text file named 'Hello text.txt' and change it to 'Hello world! Also.
This is a html message ?> 添加多个附件 This is a html message
正如上一节,添加多个附件是rasy与调用addAttachment了。在这个例子中,我会发送一个带有两个文本附件的电子邮件。
include('Mail.php');
include('Mail/mime.php');
// Constructing the email
$sender = "Leigh
$recipient = "Leigh
$subject = "Test Email"; // Subject for the email
$text = 'This is a text message.'; // Text version of the email
$html = '
$crlf = "n";
$headers = array(
'From' => $sender,
'Return-Path' => $sender,
'Subject' => $subject
);
// Creating the Mime message
$mime = new Mail_mime($crlf);
// Setting the body of the email
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
// Add an attachment
$file = "Hello World!"; // Content of the file
$file_name = "Hello text.txt"; // Name of the Attachment
$content_type = "text/plain"; // Content type of the file
$mime->addAttachment ($file, $content_type, $file_name, 0); // Add the attachment to the email
// Add a second attachment
$file = "Hello World! Again :)"; // Content of the file
$file_name = "Hello text 2.txt"; // Name of the Attachment
$content_type = "text/plain"; // Content type of the file
$mime->addAttachment ($file, $content_type, $file_name, 0); // Add the attachment to the email
$body = $mime->get();
$headers = $mime->headers($headers);
// Sending the email
$mail =& Mail::factory('mail');
$mail->send($recipient, $headers, $body);
?>