Hello to All!
I am using the mail function to send an email with php. I have a file in the server which I would like to attach to that email?
How can I use the mail function to do this?
Thanks a lot,
Nicolas
Attaching file in email
Moderator: General Moderators
You can't do it just like a **click**. Try reading this article.
Re: Attaching file in email
You may want to try this MIME message composing and sending class that makes it very simple to create messages with attachments from existing files or dynamically generated data with automatic content-type detection.xLechugasx wrote:Hello to All!
I am using the mail function to send an email with php. I have a file in the server which I would like to attach to that email?
How can I use the mail function to do this?
Nicolas
It can also send HTML messages with embedded images and even alternative text versions and attachements if you would like that.
This will work:
Regards,
Craig
Code: Select all
<?php
/*
* FileMailer - Attaches File to Email
* Unknown origin of this code - Modified by Craig Donnelly (craig@evilwalrus.com)
*/
$fileatt = "code.php"; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = "code.php"; // Filename that will be used for the file as the attachment
$email_from = "craig@develop3r.net"; // Who the email is from
$email_subject = "Heres your file..."; // The Subject of the email
$email_message = "Regards,\n\nCraig"; // Message that the email has in it
$email_to = "craig@evilwalrus.com"; // Who the email is too
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary="{$mime_boundary}"";
$email_message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset="iso-8859-1"\n" . "Content-Transfer-Encoding:7bit\n\n" .
$email_message . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name="{$fileatt_name}"\n" .
//"Content-Disposition: attachment;\n" .
//" filename="{$fileatt_name}"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$ok = @mail($email_to, $email_subject, $email_message, $headers);
if($ok){
echo "<font face=verdana size=2>The file was successfully sent!</font>";
}else{
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>Craig