0

looking for someone to help me do this.

I have a mail script on my site that I use to send emails sending the mail work fine but I want to be able to send an email with attachments and I am running into problems doing so.

here is the php for the form

<?php

// Set email variables
$email_to = 'youremail@address.com';
$email_subject = 'Form submission';

// Set required fields
$required_fields = array('fullname','email','comment');

// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);

// Set form status
$form_complete = FALSE;

// configure validation array
 $validation = array();

// check form submittal
 if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));

// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {       
    // the field has been submitted?
    if(!array_key_exists($field, $_POST)) array_push($validation, $field);

    // check there is information in the field?
    if($_POST[$field] == '') array_push($validation, $field);

    // validate the email address supplied
    if($field == 'email') if(!validate_email_address($_POST[$field]))array_push $validation, $field);
}

// basic validation result
if(count($validation) == 0) {
    // Prepare our content string
    $email_content = 'New Website Comment: ' . "\n\n";

    // simple email content
    foreach($_POST as $key => $value) {
        if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
    }

    // if validation passed ok then send the email
    mail($email_to, $email_subject, $email_content);

    // Update form switch
    $form_complete = TRUE;
}
}

function validate_email_address($email = FALSE) {
return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}

function remove_email_injection($field = FALSE) {
   return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-       Type:", "bcc:","to:","cc:"), '', $field));
}

?>
user3260707
  • 81
  • 1
  • 9

2 Answers2

0

Check this answer out: Send attachments with PHP Mail()?

I recommend using Swift mailer. I have had VERY good success with using it. Not only does it help with attachments, but it also allows you to send HTML emails without mail programs sending it to spam.

Here is some code for the plain Mail function in PHP: found here Under send mail with attachments.

<?php 
//define the receiver of the email 
$to = 'youraddress@example.com'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail( $to, $subject, $message, $headers ); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>
Community
  • 1
  • 1
Hunter Mitchell
  • 7,063
  • 18
  • 69
  • 116
0

Assume your form has this input field

<label for="Attachment">Attachment:</label>
<input type="file" name="attach1" id="attach1" />

The function below will do the job for sending the attachment, it takes parameters $recipientEmail,$senderEmail, $subject,$message, the attachment is take care by $_FILE as long as you have the above input field on form submission.

public function sendEmailWithAttachments($recipientEmail,$senderEmail, $subject,$message){
    if(isset($_FILES) && (bool) $_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);

    }   
s-hunter
  • 24,172
  • 16
  • 88
  • 130