Search code examples
phphtmlemailmimeemail-attachments

function send email with attachment error


I'm trying to create from sending mail with attachment file via PHP, but there is an error, when mail sent to mail box the message arrive with out any attachments here screen shot of mailbox

enter image description here

<?php
function mail_file($to, $from, $subject, $body, $file){

    $boundary = md5(rand());

    $headers = array(
        'MIME-Version: 1.0',
        "From: {$from}",
        "Content Type : multipart/mixed; boundary=\"{$boundary}\""

                    );

$message = array(
"--{$boundary}",
'Content-Type: text/html; charset="utf-8"',
'Content-transfer-Encoding: 7-bit',
'',
chunk_split($body),
"--{$boundary}",
"Content-Type: {file['type']}; name=\"{$file['name']}\"",
"Content-Disposition: attachment; filename=\"{$file['name']}\"",
"Content-Transfer-Encoding: base64",
'',
@chunk_split(base64_encode(file_get_contents($file['path']))),
"--{$boundary}--"
);

@mail($to, $subject, implode("\r\n", $message), implode("\r\n", $headers));     

        }

        if($_SERVER['REQUEST_METHOD'] =='POST'){
    $file = array (

    'name' => $_FILES['file']['name'],
    'size' => $_FILES['file']['size'],
    'type' => $_FILES['file']['type'],
    'path' => $_FILES['file']['tmp_name']
    );



    mail_file('fahmy.farahat@gmail.com', 'File from <fahmy.farahat@gmail.com>', 'a file up', $body, $file);
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>send mail</title>
</head>

<body>


<form action="" method="post" enctype="multipart/form-data">
<label>Name</label><br />

<input type="text" name="name" id="name" />
<br /><br />


<input type="file" name="file" id="file"/>
<br />

<input type="submit" value="email file" />

</form>
</body>
</html>

Solution

  • The mail header should read Content-Type, not Content Type.