Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I'm using PHP to send an email from contact form with attachment.
I have 2 problems:
1- it doesn't work on localhost.
2- on the server where the website is hosted it worked only when sending to GMAIL account but without sending the attachment.
The website is very simple just HTML pages, this is the only page that I need to use server code to send an email.


Please advise what I'm doing wrong
Thank you

What I have tried:

HTML code:
HTML
<pre><!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='sendEmail.css'/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<script type='text/javascript' src='validateEmail.js'></script>
</head>
<body>
    <form name="contactform" class="contactform" method="post" onsubmit="return validateForm()"  action="sendEmail.php">
        <label>Sender Email:</label>
        <input type="text" id="semail" name="semail" />
        <label>Recipient Email:</label>
        <input type="text" id="remail" name="remail" value="" />
        <label for="Subject">Subject:</label>
        <input type="text" name="Subject" id="Subject" />
        <label for="Attachment">Attachment:</label>
        <input type="file" name="attach1" id="attach1" />
        <label for="Message">Message:</label><br />
        <textarea name="Message" rows="20" cols="20" id="Message"></textarea>
        <div class="submit-btn">
        <input type="submit"/>
        </div>
    </form>
</body>
</html>


PHP code:
PHP
<pre><?php
ini_set('display_errors', 1);
$senderEmail = filterInput($_POST['semail']);
$recipientEmail = filterInput($_POST['remail']); 
$message = filterInput($_POST['Message']);
$subject = filterInput($_POST['Subject']);
 
/* echo $senderEmail.$recipientEmail.$message.$subject; */
if(sendEmailWithAttachments($recipientEmail,$senderEmail,$subject,$message))
{
    echo "Email sent successfully!";
}
else
{
    echo "Failed to send the email...";
}
 
function filterInput($data)
{
     $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
     return $data;
}
function sendEmailWithAttachments($recipientEmail,$senderEmail,$subject,$message){
 
     
    if(isset($_FILES)) {

        $allowedExtensions = array("pdf","doc","docx"); /*,"gif","jpeg","jpg","JPG","png","PNG","rtf","txt","xml"*/
 
        $files = array();
        foreach($_FILES as $name=>$file) {
            //die("file size: ".$file['size']);
            if($file['size']>=5242880)//5mb
            {
                $fileSize=$file['size'];
                return false;
            }
            $file_name = $file['name']; 
            $temp_name = $file['tmp_name'];
            $file_type = $file['type'];
            $path_parts = pathinfo($file_name);
            $ext = $path_parts['extension'];
            if(!in_array($ext,$allowedExtensions)) {
                return false;
                die("File $file_name has the extensions $ext which is not allowed");
            }
 
            //move the file to the server, cannot be skipped
            $server_file="/tmp/$path_parts[basename]";
            move_uploaded_file($temp_name,$server_file);
            array_push($files,$server_file);
            //array_push($files,$temp_name);
        }
 
        // email fields
        $headers = "From: $senderEmail";
 
 
        // boundary 
        $semi_rand = md5(time()); 
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
        // headers for attachment 
        $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
 
        // multipart boundary 
        $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
        $message .= "--{$mime_boundary}--\n";
 
        // preparing attachments
        for($x=0;$x<count($files);$x++){
            $file = fopen($files[$x],"rb");
            $data = fread($file,filesize($files[$x]));
            fclose($file);
            $data = chunk_split(base64_encode($data));
            $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
            "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
            "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            $message .= "--{$mime_boundary}\n";
        }
 
        // send
        return mail($recipientEmail, $subject, $message, $headers); /*@mail*/
 
    }
}   
Posted
Updated 18-Sep-17 21:01pm
v3

1 solution

Quote:
1- it doesn't work on localhost.
Check your PHP configuration (php.ini) regarding the mail setup. Check your Firewall settings.

Quote:
2- on the server where the website is hosted it worked only when sending to GMAIL account but without sending the attachment.
Have you tested other mail servers? If yes, have you changed PHP mail configuration accordingly?
PHP
$headers = "From: $senderEmail";
This line may be the reason that the mail is not send on localhost or to other servers. Many SMTP servers will only accept mails where the From matches their own domain(s).

As already suggested in my answer to your previous post: Have you inspected the raw content (plain text) of the received mail to check if it is in a valid format?

In my previous answer I noted that mails should use CRLF (\r\n) terminated lines but you are still using single LF. While most mail programs accept LF terminated lines, you should not rely on that. With Windows, you should also set sendmail_from in php.ini.

This line contains an invalid content type:
PHP
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " // ...

At least the above line and not using CRLF makes your mail not a valid (RFC conform) one. When creating mail content you should ensure that it is valid which requires knowing the format by reading the corresponding RFCs.
 
Share this answer
 
Comments
Samira Radwan 19-Sep-17 18:12pm    
That was helpful, thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900