Showing posts with label mail. Show all posts
Showing posts with label mail. Show all posts

Friday, 1 October 2010

Send a file attachment and send as an e-mail in PHP

This is not the full story. First you need a form to collect the data and put it in a field (in this case) called myValue.

This piece of code takes the field contents, creates a text file and sends it.


<?php
    $filetitle = "testFile.txt";  
    $data = $_POST["myValue"]);
    $to = 'jimmy@googlemail.com';
    $subject = 'My subject';  
    $filetype = "text/plain";  
    $email_from = "jammy@googlemail.com";  
    $headers = "From: ".$email_from;      
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";
  
    $email_message .= "This is a multi-part message in MIME format.\n\n" .
    "--{$mime_boundary}\n" .
    "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .
    $email_message . "\n\n";
  
    $data = chunk_split(base64_encode($data));
  
    $email_message .= "--{$mime_boundary}\n" .
    "Content-Type: {$filetype};\n" .
    " name=\"{$filetitle}\"\n" .  
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "--{$mime_boundary}--\n";
  
    $ok = @mail($to, $subject, $email_message, $headers);

    if($ok)
    {
        echo "It worked";
    }
    else
    {
        die("It failed");
    }
?>