PHP e-mail attachment script

Posted by Olaf #

This simple PHP script or e-mail function is able to send a plain text e-mail message including a single attached file. The file has to be uploaded first or there should be an existing file on your web server. There are better and more advanced PHP scripts on the Internet, but I hope this script will help your to understand how to send e-mail attachment using some short PHP code.

This custom PHP function will show the (beginning) PHP developer how-to build an e-mail script with attachment function. Please note that inside the mail function is no validation functionality available.

<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}
?>

Next we show an example on how-to use this function to send an e-mail message with one attached zip file:

$my_file = "somefile.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);

Are you looking for a script to send multiple attachments? Try our mail attachment class script.

If you like to send your websites mail messages via SMTP and Gmail, check our PHPMailer tutorial, too.

Comments / discussions

Posted by praveenkrg #

Hi Olaf,

I tried with your example. Mail sends with an attachment. But the size of attach zip file become 0 byte. So the zip file could not work.

I don't know whats the problem

Any help will be appreciated.

Thanks in advance,
Praveen

Posted by Olaf #

Hi,
maybe the path to the file is not right?

check this row first:
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";

maybe you need to use a static path?

Posted by praveenkrg #

Thanks for immediate reply

I checked the this row
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";

My directory structure is like this:
www.domain.com/foldername/zipfilename.zip

When I try with static link it gives warnings:

Warning: filesize() [function.filesize]: stat failed for www.domain.com/foldername/zipfilename.zip on line 191

Warning: fopen(www.domain.com/foldername/zipfilename.zip) [function.fopen]: failed to open stream: No such file or directory

Warning: fread(): supplied argument is not a valid stream resource

Warning: fclose(): supplied argument is not a valid stream resource
mail send ... OK

Any idea?

Posted by Olaf #

that's what I thought :)

A document root is something else, create a new file and check the doc root using:

echo $_SERVER['DOCUMENT_ROOT']

Posted by praveenkrg #

sorry didn't understood.

can you elaborate, what should i change and where to change?

Posted by Olaf #

You need to learn what your document root is, this path is required to open a file with PHP.

create a new file and add this code:

<?php echo $_SERVER['DOCUMENT_ROOT']; ?>

Run this script in your browser, the result is the document root.

Next you need to check if this is confirm the place where the attachment is located.

Posted by praveenkrg #

when I run the above script on local system it prints "C:/xampp/htdocs"

And when I run the script on server it prints: "D:\Hosting\4836046\html"

my server directory structure is like this:
www.domain.com/foldername/zipfilename.zip

Posted by Olaf #

Windows server and document root are always a problem.

I never used PHP on windows, check this PHP function (and read the comments)
http://php.net/manual/en/function.getcwd.php

maybe that your hosting provider know how to identify the doc root from your account?

Posted by praveenkrg #

Ok I understood the problem. I will ask my service provider.

But the mail I am getting this time is containing the 0 bytes zip file attachment. Is this problem because of doc root?

Posted by Olaf #

yes, the script can't include the file data (only the mail header for this attachment is send)

Posted by praveenkrg #

Hi Olaf,

My hosting provider replied.
Absolute Hosting Path: D:\Hosting\4836046\html

Now what's next step?

Posted by Olaf #

Sorry I can't say how you do this in Windows :(
(I use windows only to work in photoshop)

First you need to find a way to handle those paths in PHP on windows.
I'm sure Google has a lot of information on that.

On linux I have one file (config.php) in the doc root, creating this constant variable:
define('DOC_ROOT', dirname(__FILE__).'/');

Next I include this file in my PHP scripts, let's say the script is one level above the root I use
include_once '../config.php'

After including that file I'm able to use the variable DOC_ROOT in my scripts. This way the server var DOCUMENT_ROOT is not needed anymore.

I hope that helps.

Posted by praveenkrg #

Thanks for your advice. I will try to find alternate solution for this.

One more thing I just tried your code with my other hosting(linux, php).

mail function is giving warning.
--
Warning: mail() [function.mail]: Bad parameters to mail() function, mail not sent. in /home/content/b/e/s/bestjobs1/html/corporate_reg/mail_attach.php on line 26
mail send ... ERROR!
--
any idea?

Posted by Olaf #

I think this is related to the paths as well.
If you can't get this under your fingers you will fail in PHP

try a simple mail command first:
mail('mail@domain.com', 'mail subject', 'my first mail send via PHP');

Posted by praveenkrg #

Hi Olaf,

Thanks for your support and help.

I did it my self.

--Removed 3rd party code--

Posted by Olaf #

Hi,

great that you found a working solution.
I removed your code because it's not tested and might not safe.