Thursday, January 14, 2010

How to Write a File to Email by PHP

The contents of a file can be place sent in an email by using the "fread" and "mail" functions. The "fread" function is used to place the contents of the file into a variable. The file must be first opened using the "fopen" function and it should be closed using the "fclose" function. The script must also have variables for the sender address, the recipient address and the subject line for the email. These variables are used to create the headers that are sent, along with the contents of the document, using the "mail" function.

Instructions
  1. Step 1

    Open blank document in your preferred text editor.

  2. Step 2

    Type "

  3. Step 3

    Type the following four lines to place the contents of the file in the "$data" variable:
    $file="test.txt";
    $fh=fopen($file,'r');
    $data=fread($fh, filesize($file));
    fclose($fh);

  4. Step 4

    Type the following two lines to set up the sender and recipient email addresses:
    $to_address="recipient@example.com";
    $from_address="sender@example.com";

  5. Step 5

    Type the line "$subject="File Contents";" to create the subject of the email.

  6. Step 6

    Type the following three lines to set up the email headers:
    $headers = 'From: '.$from_address."\r\n".
    'Reply-To: '.$from_address."\r\n" .
    'X-Mailer: PHP/' . phpversion();

  7. Step 7

    Type the line "mail($to_address, $subject, $data, $headers);" to send the email containing the contents of the file.

  8. Step 8

    Type "?>" to close the PHP script.

  9. Step 9

    Save the script with the ".php" file extension.

No comments:

Post a Comment