php mail function with image/documents attachment

2
2083
php sends out mail with attachment
php sends out mail with attachment

This PHP mail Function script is able to send a plain text email message together with a single attachment file.

You probably know how to send email with PHP using php mail function, it’s just few lines of code, but it gets bit tricky when you want to send an attachment with PHP email and should be able to deliver emails to Gmail and Hotmail without regarding as SPAM..

PHP mail Function
PHP mail Function

#1 Why send attachment using php mail function ?

Alright you probably have witnessed sending attachment such images or document files to your recipient and you wonder how possible you are going to do so since you only know basic method of sending mail using php which can only send message in text form only to its mail recipient since php programming language comes with mail function

About PHP’s native mail() function

A workaround for sending attachment using PHP mail() is to construct a MIME header which contains the attachment information. The following piece of codes should help.

Php Native function for mailing
Php Native function for mailing

Below i provide the complete PHP code that sends PHP email with attachment. Just create a PHP file with code below and point your HTML form to the file, and don’t forget to change recipient address and domain email address in the code.

By default, the PHP mail() does not support sending email with attachment. In order to send an attachment, u can either use the PEAR package or PHPMailer. But in reality, the hosting server may not provide these kinds of third party libraries.

Basic method of sending mail using php without attachment

Problem 1: Enters spam frequently

This is a basic way you can send message using php built mail function. Note: the below is php official documentary example of sending plain text message using php.

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Many times trying to send message using the above basic method seems to work but will definitely trap your messages in the spam due to spam filter policy of most mail servers.

Alternative method of sending mail using php without attachment

Solution 1: escapes spam sometimes

This alternative is a proven test working script example that seems to avert all the spam filter policy and hits the receivers inbox like a charm though it is a spoof script for legal use only.

<?php

	// COMPOSE
	$to      = 'angelina@jolie.com';
	$subject = 'Hey, pardon me.';
	$message = 'I want to be frank with you!';
	

	// FULL HEADER
	$headers  = "From: testsite < mail@testsite.com >\n";
	$headers .= "Cc: testsite < mail@testsite.com >\n"; 
	$headers .= "X-Sender: testsite < mail@testsite.com >\n";
	$headers .= 'X-Mailer: PHP/' . phpversion();
	$headers .= "X-Priority: 1\n";
	$headers .= "Return-Path: mail@testsite.com\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-Type: text/html; charset=iso-8859-1\n";
	
	
	// SEND AND SHOW MESSAGE
	mail($to, $subject, $message, $headers);
	
    ?>

#2 How this php script that send mail with attachment works

So, today let’s find-out how we can send email with an attachment using PHP mail.

  1. Create a HTML form with file input field in a file called index.php
  2. Styled the HTML form to atleast look prettier just adding above the html form codes the below css codes
  3.  enctype attribute of the HTML form should be “multipart/form-data“, so that form-data is encoded as “multipart/form-data” when sent to server.
  4. Form action link href=”” linked to the spoof php mailer with attachment in mail.php

A workaround for sending attachment using PHP mail() is to construct a MIME header which contains the attachment information. The following piece of codes should help.

Below i provide the complete PHP code that sends PHP email with attachment. Just create a PHP file with code below and point your HTML form to the file, and don’t forget to change recipient address and domain email address in the code.

HTML Mailing Form for the example ( php mail function with image/documents attachment ) index.php

<div class="form-style-3">
<form role="form" action="mail.php" method="post" enctype="multipart/form-data">
<fieldset><legend>Email spoofed info</legend>
<label for=""><span>From (name):<span class="required">*</span></span>
<input class="form-control" id="inputdefault" type="text" name="fromname" placeholder="From name" required /></label>
<label for=""><span>From (Email):<span class="required">*</span></span>
<input class="form-control" id="inputdefault" type="text" name="fromemail" placeholder="From email" required /></label>
</fieldset>
<fieldset><legend>Reply E-mail</legend>
<label for=""><span>Replyto (name)</span>
<input class="form-control" id="inputdefault" type="text" name="replytoname" placeholder="Reply-to(name)" required /></label>
<label for=""><span>Reply-to (email):</span>
<input class="form-control" id="inputdefault" type="text" name="replytoemail" placeholder="Reply-to E-mail" required /></label>
</fieldset>

<fieldset><legend>Client mail</legend>
<label for=""><span>To (Receiver email):<span class="required">*</span></span>
<input class="form-control" id="inputdefault" type="text" name="to" placeholder="Receiver email" required /></label>
</fieldset>
<fieldset><legend>Message</legend>
<label for=""><span>Subject:<span class="required">*</span></span>
<input class="form-control" id="inputdefault" type="text" name="subject" placeholder="Subject: Activate peoples info" required /></label>
<label for=""><span>Message:<span class="required">*</span></span>
<textarea rows="7" cols="70" name="message" maxlength="10000" placeholder="write messages here....."></textarea></label>
</fieldset>
<fieldset><legend>Upload attachement</legend>
<label for=""><span>files 1:<span class="required">*</span></span>
<input class="form-control" id="inputdefault" type="file" name="my_files[]" value="" accept="image/*" size="23"></label>
<label for=""><span>files 2:</span>
<input class="form-control" id="inputdefault" type="file" name="my_files[]" value="" accept="image/*"></label>
<label><span></span> <input id="inputdefault" type="submit" value="Send Now" name="submitnow" class="btn btn-primary form-control">
</label>
</fieldset>
</form>
</div>

style css code for the html form

<style type="text/css">
.form-style-3{
	max-width: 50%;
	font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
.form-style-3 label{
	display:block;
	margin-bottom: 10px;
}
.form-style-3 label > span{
	float: left;
	width: 100px;
	color: #F072A9;
	font-weight: bold;
	font-size: 13px;
	text-shadow: 1px 1px 1px #fff;
}
.form-style-3 fieldset{
	border-radius: 10px;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	margin: 0px 0px 10px 0px;
	border: 1px solid #FFD2D2;
	padding: 20px;
	background: #FFF4F4;
	box-shadow: inset 0px 0px 15px #FFE5E5;
	-moz-box-shadow: inset 0px 0px 15px #FFE5E5;
	-webkit-box-shadow: inset 0px 0px 15px #FFE5E5;
}
.form-style-3 fieldset legend{
	color: #FFA0C9;
	border-top: 1px solid #FFD2D2;
	border-left: 1px solid #FFD2D2;
	border-right: 1px solid #FFD2D2;
	border-radius: 5px 5px 0px 0px;
	-webkit-border-radius: 5px 5px 0px 0px;
	-moz-border-radius: 5px 5px 0px 0px;
	background: #FFF4F4;
	padding: 0px 8px 3px 8px;
	box-shadow: -0px -1px 2px #F1F1F1;
	-moz-box-shadow:-0px -1px 2px #F1F1F1;
	-webkit-box-shadow:-0px -1px 2px #F1F1F1;
	font-weight: normal;
	font-size: 12px;
}
.form-style-3 textarea{
	width:250px;
	height:100px;
}
.form-style-3 input[type=text],
.form-style-3 input[type=date],
.form-style-3 input[type=datetime],
.form-style-3 input[type=number],
.form-style-3 input[type=search],
.form-style-3 input[type=time],
.form-style-3 input[type=url],
.form-style-3 input[type=email],
.form-style-3 select, 
.form-style-3 textarea{
	border-radius: 3px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	border: 1px solid #FFC2DC;
	outline: none;
	color: #F072A9;
	padding: 5px 8px 5px 8px;
	box-shadow: inset 1px 1px 4px #FFD5E7;
	-moz-box-shadow: inset 1px 1px 4px #FFD5E7;
	-webkit-box-shadow: inset 1px 1px 4px #FFD5E7;
	background: #FFEFF6;
	width:50%;
}
.form-style-3  input[type=submit],
.form-style-3  input[type=button]{
	background: #EB3B88;
	border: 1px solid #C94A81;
	padding: 5px 15px 5px 15px;
	color: #FFCBE2;
	box-shadow: inset -1px -1px 3px #FF62A7;
	-moz-box-shadow: inset -1px -1px 3px #FF62A7;
	-webkit-box-shadow: inset -1px -1px 3px #FF62A7;
	border-radius: 3px;
	border-radius: 3px;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;	
	font-weight: bold;
}
.required{
	color:red;
	font-weight:normal;
}
</style>

Problem 2: *The worst of sending mails using php script

Well, I will tell you this, it is frustrating mostly trying to send mail that contains attachment to someone and you probably succeed but just to notice that your mail is trapped forever in the receivers spam / junk box

Solution 2: *The worst of sending mails using php script

Shopinson solved this problem using spoof php mail script to send plain text email with attachment be it any document type (.doc .jpeg .pdf) to anyone without being trapped in the spam.

The php script for the main work in mail.php

<?php 						
if(isset($_POST["submitnow"])){
   						$fromname = $_POST["fromname"];
                        $fromemail = $_POST["fromemail"];
                        $replytoname = $_POST["replytoname"];
                        $replytoemail = $_POST["replytoemail"];
                        $to = $_POST["to"];
                        $subject = $_POST["subject"];
                        $message = $_POST["message"];

    //php validation, exit outputting json string
	// CREATE FULL FIELDS (NAME + EMAIL)
	$fromFull 	=  $fromname . ' <'.$fromemail.'> ';
	$replytoFull 	=  $replytoname . ' <'.$replytoemail.'> ';



    $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
	//$mgs = "".$message;
	//$message        = filter_var($mgs, FILTER_SANITIZE_STRING); //capture message

    $attachments = $_FILES['my_files'];
    
    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("shopinson.com"); 
    
    //construct a message body to be sent to recipient
    //$message_body =  "------------------------------\n";
    $message_body =  "$message\n";

    
    if($file_count > 0){ //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers  = "From: ".$fromFull . "\r\n";
        $headers .= "Reply-To: ".$replytoFull . "\r\n";
    	// $headers .= "To: Mary <mary@example.com>, Kelly <kelly@example.com>" . "\r\n";
		// $headers .= "Cc: sendacopy@here.com" . "\r\n";
		// $headers .= "Bcc: sendablindcopy@here.com" . "\r\n";
		// $headers .= "X-Sender: testsite < mail@testsite.com >" . "\r\n";
		// $headers .= "Return-Path: " . $fromFull . "\r\n";
		// $headers .= "Content-Type: text/html; charset=ISO-8859-1" . "\r\n";
	$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
	$headers .= "X-Priority: 1" . "\r\n";
	
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n"; 
        
        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; 
        $body .= chunk_split(base64_encode($message_body)); 

        //attachments
        for ($x = 0; $x < $file_count; $x++){       
            if(!empty($attachments['name'][$x])){
                
                if($attachments['error'][$x]>0) //exit script and output error if we encounter any
                {
                    $mymsg = array( 
                    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
                    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
                    3=>"The uploaded file was only partially uploaded", 
                    4=>"No file was uploaded", 
                    6=>"Missing a temporary folder" ); 
                    print  $mymsg[$attachments['error'][$x]]; 
                    exit;
                }
                

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];
                
                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
                
                $body .= "--$boundary\r\n";
                $body .="Content-Type: $file_type; name=".$file_name."\r\n";
                $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
                $body .="Content-Transfer-Encoding: base64\r\n";
                $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n"; 
                $body .= $encoded_content; 
            }
        }

    }else{ //send plain email otherwise
	// FULL HEADER
	$headers  = "From: ".$fromFull . "\r\n";
	$headers .= "Reply-To: ".$replytoFull . "\r\n";
	// $headers .= "To: Mary <mary@example.com>, Kelly <kelly@example.com>" . "\r\n";
	// $headers .= "Cc: sendacopy@here.com" . "\r\n";
	// $headers .= "Bcc: sendablindcopy@here.com" . "\r\n";
	// $headers .= "X-Sender: testsite < mail@testsite.com >" . "\r\n";
	// $headers .= "Return-Path: " . $fromFull . "\r\n";
	// $headers .= "Content-Type: text/html; charset=ISO-8859-1" . "\r\n";
	$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
	$headers .= "X-Priority: 1" . "\r\n";
	$headers .= "MIME-Version: 1.0" . "\r\n";
        $body = $message_body;
    }

    $sentMail = mail($to, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {       
        print 'Thank you for your email';
        exit;
    }else{
        print 'Could not send mail! Please check your PHP mail configuration.';  
        exit;
    }
}
?>

Well finally this script above allows you to send email both plain text with or without attachments.

That is if attach document or not it will still deliver the mail the recipient inbox.

2 COMMENTS

  1. Let me start by thanking you for making your script freely available I really appreciate that.
    I have read your article here https://shopinson.com/php-mail-function-image-documents-attachment/ carefully and then I have copied and pasted the HTML and the PHP script into appropriate files and have uploaded them to my website
    I have encountered a problem though when I try to utilise the form. I get this error message “Please check your PHP mail configuration.”
    I am of course too much of a novice at PHP to actually have any idea where the problem could be. Plus the other thing is, I haven’t touched any of the coding – at all.
    My understanding of your form is that it collects all the material (email addresses and file info etc) from the input windows within the HTML form, that it needs in order to deliver the outcome
    Except for this my import into those windows I have not done anything else – am I missing some procedure that I have not completed

    My Regards

    Warren

  2. alright then bolton if i understand that it prompt error as explain in your comment here

    But this can be made right when you fill in the FROM EMAIL to be yours (domain assigned)
    STEPS TO CREATE EMAIL IN CPANEL
    for example you have to create a mail from your cpanel to be like admin@chinacrap.info or anything@chinacrap.info then come back to your email sender form include it in the FROM EMAIL then you can write anything in other fields then hit the send button lets know what you got

LEAVE A REPLY

Please enter your comment!
Please enter your name here