Simple PHP script to send email with file attached.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
harrytheshark
Forum Newbie
Posts: 3
Joined: Sun Apr 05, 2009 5:37 am

Simple PHP script to send email with file attached.

Post by harrytheshark »

I'm a Cocoa developer with a very limited knowledge of PHP and what I'm looking for is some code that will send a file I'm uploading to my email address.

At the moment, I'm just writing the uploaded file to a directory on my server.

Code: Select all

<?php
$target_path = "";
$target_path = $target_path . basename( $_FILES['uploadFile']['name']); 
if(move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadFile']['name']). 
    " has been uploaded";
} else{
    echo "Error!";
}
?>
I can also send an email with some simple code:

Code: Select all

<?php 
$emailAddress = $_POST['email']; 
$me = "me@domain.com";
$headers = "From: $emailAddress";
mail($me, "Some Subject", "Some body", $headers); 
?>
What I'm unsure about is to combine the two together.
I did consider saving the file to a directory, then email a link to the file, but I don't really want to keep the file stored when it doesn't need to be for security reasons.

If anyone would mind helping me out, I would be very grateful.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Simple PHP script to send email with file attached.

Post by Christopher »

See the PHP manual page for examples of each parameter -- especially the headers. http://us3.php.net/manual/en/function.mail.php

Also, you may want to use something like SwiftMailer which simplifies attachments.
(#10850)
Post Reply